<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="order_form">
      <el-row>
        <el-col :span="12">
          <el-form-item label="订单号" prop="F_Id" >
            <el-input v-model="ruleForm.F_Id" placeholder="请输入订单号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消息来源" prop="F_ADFrom" >
            <el-input v-model="ruleForm.F_ADFrom" placeholder="请输入消息来源"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="F_Customer">
            <el-input v-model="ruleForm.F_Customer" placeholder="请输入客户姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="F_CustomerPhone">
            <el-input v-model="ruleForm.F_CustomerPhone" placeholder="请输入手机号码" @change="changeCustomerPhone" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="商品">
        <el-table :data="commodityTableData" stripe style="width: 100%">
          <el-table-column prop="F_ProductName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="F_Count" label="商品数量" align="center"></el-table-column>
        </el-table>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="订单类型" prop="F_Type" >
            <el-select v-model="ruleForm.F_Type" class="form_select" filterable clearable placeholder="请选择订单类型">
              <el-option v-for="item in orderType" :key="item.F_Value" :label="item.F_Value" :value="item.F_Value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出库货仓" >
            <el-select v-model="ruleForm.F_Stock" placeholder="请选择出库货仓" class="form_select" clearable>
              <el-option
                v-for="item in stockList"
                :key="item.F_Value"
                :label="item.F_Value"
                :value="item.F_Value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收件人" >
            <el-input v-model="ruleForm.F_Addressee" placeholder="请输入收件人"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收件人手机号" >
            <el-input v-model="ruleForm.F_AddPhone" placeholder="请输入收件人手机号" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="送货说明" >
            <el-input v-model="ruleForm.F_AddDes" placeholder="请输入送货说明"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="省" prop="F_AddProvince">
            <el-select v-model="ruleForm.F_AddProvince" class="form_select" value-key="id" filterable clearable placeholder="请选择省" @change="getCity" >
              <el-option v-for="item in provinceDatas" :key="item.id" :label="item.text" :value="item" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="市" prop="F_AddCity">
            <el-select v-model="ruleForm.F_AddCity" class="form_select" value-key="id" filterable clearable placeholder="请选择市" @change="getArea" >
              <el-option v-for="item in cityDatas" :key="item.id" :label="item.text" :value="item" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区/县" prop="F_AddArea">
            <el-select v-model="ruleForm.F_AddArea" class="form_select" value-key="id" filterable clearable placeholder="请选择区/县" @change="getTown">
              <el-option v-for="item in areaDatas" :key="item.id" :label="item.text" :value="item" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="乡镇/街道" prop="F_AddTown">
            <el-select v-model="ruleForm.F_AddTown" class="form_select" value-key="id" filterable clearable placeholder="请选择乡镇/街道" @change="sleectTown" >
              <el-option v-for="item in townDatas" :key="item.id" :label="item.text" :value="item" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="详细地址" prop="F_Address">
            <el-input v-model="ruleForm.F_Address" placeholder="请输入详细地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮编" >
            <el-input v-model="ruleForm.F_PostalCode" placeholder="请输入邮编" onkeyup="value=value.replace(/[^\d.]/g,'')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="快递" >
            <el-select v-model="ruleForm.F_Express" placeholder="请选择快递" class="form_select" clearable>
              <el-option
                v-for="item in expressList"
                :key="item.F_Value"
                :label="item.F_Value"
                :value="item.F_Value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='12'>
          <el-form-item label="运费" prop="F_ExpressFee" >
            <el-select v-model="ruleForm.F_ExpressFee" placeholder="请选择运费" class="form_select" clearable>
              <el-option label="10" value="10"></el-option>
              <el-option label="28" value="28"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式" >
            <el-select v-model="ruleForm.F_PayType" placeholder="请选择支付方式" class="form_select" clearable>
              <el-option v-for="item in payTypeList" :key="item.F_Value" :label="item.F_Value" :value="item.F_Value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label="使用积分" prop="F_Score" >
            <el-input v-model.number="ruleForm.F_Score" placeholder="请输入使用积分"/>
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label="拥有积分" >
            <span>{{ alreadyPoints }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="推荐人" prop="F_RecommendName" >
            <el-select v-model="ruleForm.F_RecommendName" class="form_select" filterable remote reserve-keyword clearable value-key="F_ID" placeholder="请输入电话号码" :remote-method="remoteMethodRecommend" :loading="loading" @change="recommendChangeSelect">
              <el-option v-for="item in recommendListOptions" :key="item.F_ID" :label="item.F_Name" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属人" prop="F_BelongName" >
            <el-select v-model="ruleForm.F_BelongName" class="form_select" filterable remote reserve-keyword clearable value-key="F_UserId" placeholder="请输入归属人" :remote-method="remoteMethodBelong" :loading="loading" @change="belongChangeSelect">
              <el-option v-for="item in belongListOptions" :key="item.F_UserId" :label="item.F_UserName" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="F_Remark">
        <el-input :autosize="{ minRows: 4}" v-model="ruleForm.F_Remark" type="textarea" placeholder="请输入备注"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(0)">保存</el-button>
        <el-button type="primary" @click="submitForm(1)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProviceCity, getDictionaryValueList } from '@/api/commonAPI'
import { getOrder } from "@/api/orderManagement/orderList";
import { getAfterSaleEditOrderList } from "@/api/afterSaleManagement/afterSaleList";
import { validateTel } from '@/utils/validate'
import { delFiles, filterContent, pickerOptions } from '@/utils'
import { getAreaTreeChildNode } from '@/api/systemSetup/roleSetting/areaManagement'
import { getOrderLists } from '@/api/memberManagement/memberList'
import { getUserAccountLists } from '@/api/systemSetup/roleSetting/userManage'

const validateTelRule = (rule, value, callback) => {
  if (!validateTel(value)) {
    callback(new Error('请输入有效的手机号码!'))
  } else {
    callback()
  }
}

export default {
  name: "AddOrEdit",
  props: {
    rowid: {
      type: String,
      default: ""
    },
    layerid: {
      type: String,
      default: ""
    }
  },
  filters: {
  },
  data() {
    return {
      provinceDatas: [], // 省下拉数据
      cityDatas: [], //市下拉数据
      areaDatas: [], //区/县下拉数据
      townDatas: [], //乡镇/下拉数据
      stockList: [], //出库货仓下拉数据
      expressList: [], //快递
      payTypeList: [], //支付方式
      recommendList: [], //会员列表数据
      recommendListOptions: [], //会员列表数据
      belongList: [], //归属人列表数据
      belongListOptions: [], //归属人列表数据
      commodityTypeLists: [], //商品分类下拉数据
      commodityTableData: [], //添加商品
      activityAccountData: [], //活动核算数据
      orderType: [],//订单类型
      pickerOptions, // 日期数据
      alreadyPoints: '', //已拥有积分
      ruleForm: {
        F_Customer: '', //是 sring 客户姓名
        F_CustomerPhone: '', //是 sting 手机号码
        F_ADFrom: '', //是 string 消息来源
        F_Type: '', //是 sring  订单类型
        F_Id: '', //是 string 订单号
        OrderDetailList: [], //订单详情list
        UseActList: [], //活动详情list
        F_State: '', //是 string 订单状态
        F_TrackingNo: '', //否 string 快递单号
        F_Addressee: '', //否 string 收件人
        F_AddPhone: '', //否 string 收件人手机号
        F_AddDes: '', //否 string 送货说明
        F_AddProvince: '', //否 string 省
        F_AddCity: '', //否 string 市
        F_AddArea: '', //否 string 区/县
        F_AddTown: '', //否 string 乡/镇
        F_Address: '', //否 string 详细地址
        F_PostalCode: '', //否 string 邮编
        F_Express: '', //否 string 选择的快递
        F_ExpressFee: '10', //否 number 运费
        F_PayType: '', //否 string  支付方式
        F_Stock: '', //否 string 出货仓库
        F_RealPrice: 0, //否 number 实收金额
        F_Score: '', //否 number  使用积分
        F_RecommendId: '',// 否 number 推荐人id
        F_RecommendName: '', //否 string 推荐人名称
        F_Belong: 0, //否 number 归属人id
        F_BelongName: '', //否 string 归属人名称
        F_Remark: '', //否 string 备注
      },
      rules: {
        F_Customer: [{
          required: true,
          trigger: 'blur',
          message: '请输入客户姓名',
        }],
        F_CustomerPhone: [{
          required: true,
          trigger: 'blur',
          validator: validateTelRule
        }],
        F_ADFrom: [{
          required: true,
          trigger: 'blur',
          message: '请输入消息来源',
        }],
        F_Type: [{
          required: true,
          trigger: 'change',
          message: '请输入订单类型',
        }],
        F_Id: [{
          required: true,
          trigger: 'blur',
          message: '请输入订单号',
        }],
        F_Score: [{
          required: false,
          trigger: 'blur',
          message: '请输入使用积分',
        },{
          type: 'number',
          message: '使用积分必须为数字'
        }],        
      },
      loading: false
    };
  },
  created() {
    this.getRecommendList()
    this.getBelongList()
    this.getStock()
    this.getOrderType()
    this.getExpress()
    this.getPayType()
    this.getProvince()
    Promise.all([
    ]).then(() => {
      if (this.rowid) {
        this.getDetail(this.rowid);
      }
    });
  },
  methods: {
    submitForm(state) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.ruleForm.F_State = state
          this.ruleForm.F_ExpressFee = this.ruleForm.F_ExpressFee == '' ? 0 : this.ruleForm.F_ExpressFee
          this.ruleForm.F_Score = this.ruleForm.F_Score == '' ? 0 : this.ruleForm.F_Score
          // 编辑
          getAfterSaleEditOrderList(this.ruleForm)
            .then(response => {
              this.loading = false;
              if (response.state.toLowerCase() === "success") {
                this.$parent.$layer.close(this.layerid);
                this.$parent.getList(); // 重新加载父级数据
                this.$message.success("恭喜你，工单信息编辑成功!");
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          this.$message.error("请输入有效的必填项信息!");
          return false;
        }
      });
    },
    //获取省下拉数据
    getProvince() {
      return new Promise(resolve => {
        const params = {
          pid: '1'
        }
        getAreaTreeChildNode(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.provinceDatas = response.data
          }
        })
        resolve()
      })
    },
    //获取市下拉数据
    getCity(item) {
      this.ruleForm.F_AddProvince = item.text
      return new Promise(resolve => {
        const params = {
          pid: item.id
        }
        getAreaTreeChildNode(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.cityDatas = response.data
          }
        })
        resolve()
      })
    },
    //获取区/县下拉数据
    getArea(item) {
      this.ruleForm.F_AddCity = item.text
      return new Promise(resolve => {
        const params = {
          pid: item.id
        }
        getAreaTreeChildNode(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.areaDatas = response.data
          }
        })
        resolve()
      })
    },
    //获取区/县下拉数据
    getTown(item) {
      this.ruleForm.F_AddArea = item.text
      return new Promise(resolve => {
        const params = {
          pid: item.id
        }
        getAreaTreeChildNode(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.townDatas = response.data
          }
        })
        resolve()
      })
    },
    //选中乡/镇
    sleectTown(item) {
      this.ruleForm.F_AddTown = item.text
    },
    // 获取出库货仓
    getStock() {
      return new Promise(resolve=>{
        const params={
          isleaf:true,
          code:'STOCK'
        }
        getDictionaryValueList(params).then(response=>{
          if(response.state.toLowerCase() === 'success'){
            this.stockList = response.data.Rows
          }
        })
      })
    },
    // 获取订单类型
    getOrderType() {
      return new Promise(resolve=>{
        const params={
          isleaf:true,
          code:'ORDERTYPE'
        }
        getDictionaryValueList(params).then(response=>{
          if(response.state.toLowerCase() === 'success'){
            this.orderType = response.data.Rows
          }
        })
      })
    },
    // 获取快递
    getExpress() {
      return new Promise(resolve=>{
        const params={
          isleaf:true,
          code:'EXPRESS'
        }
        getDictionaryValueList(params).then(response=>{
          if(response.state.toLowerCase() === 'success'){
            this.expressList = response.data.Rows
          }
        })
      })
    },
    // 获取支付方式
    getPayType() {
      return new Promise(resolve=>{
        const params={
          isleaf:true,
          code:'PayType'
        }
        getDictionaryValueList(params).then(response=>{
          if(response.state.toLowerCase() === 'success'){
            this.payTypeList = response.data.Rows
          }
        })
      })
    },
    //获取已有积分
    getAlreadyPoints(phone) {
      this.loading = true
      return new Promise(resolve => {
        const params = {
          pageindex: "", // int 第几页
          pagesize: "", // int 每页几条信息
          name: "", //客户姓名
          phone: phone, //手机号码
          type: "", //会员类型
          province: "", //省份
          city: "", //市
          area: "", //县区
          town: "", //乡镇
          address: "", //详细地址
          birthday: "", //会员生日
          recommender: "", //推荐人
          saleperson: "", //销售负责人
        }
        getOrderLists(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            if (response.rows.Rows.length > 1) {
              this.alreadyPoints = response.rows.Rows[0].F_Score
            }
          }
        })
        resolve()
      })
    },
    changeCustomerPhone(value) {
      this.getAlreadyPoints(value)
    },
    //获取推荐人列表
    getRecommendList() {
      this.loading = true
      return new Promise(resolve => {
        const params = {
          pageindex: '', // int 第几页
          pagesize: '', // int 每页几条信息
          name: '', //客户姓名
          phone: '', //手机号码
          type: '', //会员类型
          province: '', //省份
          city: '', //市
          area: '', //县区
          town: '', //乡镇
          address: '', //详细地址
          birthday: '', //会员生日
          recommender: '', //推荐人
          saleperson: '', //销售负责人
          contact: '', //联系频次
        }
        getOrderLists(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.recommendList = response.rows.Rows
          }
        })
        resolve()
      })
    },
    //获取推荐人
    remoteMethodRecommend(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.recommendListOptions = this.recommendList.filter(item => {
            return (item.F_Phone).toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.recommendListOptions = [];
      }
    },
    recommendChangeSelect(item) {
      this.ruleForm.F_RecommendId = item.F_ID
      this.ruleForm.F_RecommendName = item.F_Name
    },
    //获取归属人列表
    getBelongList() {
      this.loading = true
      return new Promise(resolve => {
        const params = {
          pageindex: '', // 第几页
          pagesize: '', // 每页几条信息
          keyword: '', // 否	string	模糊查询
          roleid: '', // 否	string	角色id
          deptid: '', // array  部门id 
        }
        getUserAccountLists(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.belongList = response.data.Rows
          }
        })
        resolve()
      })
    },
    //获取归属人
    remoteMethodBelong(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.belongListOptions = this.belongList.filter(item => {
            return (item.F_UserName).toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.belongListOptions = [];
      }
    },
    belongChangeSelect(item) {
      this.ruleForm.F_Belong = item.F_UserId
      this.ruleForm.F_BelongName = item.F_UserName
    },
    activityAccountSelectionChange(selection) {
      this.ruleForm.UseActList = selection
    },

    // 详情
    getDetail(rid) {
      getOrder(rid).then(response => {
        if (response.state.toLowerCase() === "success") {
          const res = response.data;
          this.ruleForm.F_Customer = res.F_Customer //客户姓名
          this.ruleForm.F_CustomerPhone = res.F_CustomerPhone //手机号码
          this.ruleForm.F_ADFrom = res.F_ADFrom //消息来源
          this.ruleForm.F_Type = res.F_Type //订单类型
          this.ruleForm.F_Id = res.F_Id //订单号
          this.commodityTableData = res.OrderDetailList //商品详情list
          this.ruleForm.UseActList = res.UseActList //活动详情list
          this.ruleForm.F_State = res.F_State//订单状态
          this.ruleForm.F_TrackingNo = res.F_TrackingNo //快递单号
          this.ruleForm.F_Addressee = res.F_Addressee //收件人
          this.ruleForm.F_AddPhone = res.F_AddPhone //收件人手机号
          this.ruleForm.F_AddDes = res.F_AddDes //送货说明
          this.ruleForm.F_AddProvince = res.F_AddProvince //省
          this.ruleForm.F_AddCity = res.F_AddCity //市
          this.ruleForm.F_AddArea = res.F_AddArea //区/县
          this.ruleForm.F_AddTown = res.F_AddTown //乡/镇
          this.ruleForm.F_Address = res.F_Address //详细地址
          this.ruleForm.F_PostalCode = res.F_PostalCode //邮编
          this.ruleForm.F_Express = res.F_Express + '' //选择的快递
          this.ruleForm.F_ExpressFee = res.F_ExpressFee //运费
          this.ruleForm.F_PayType = res.F_PayType //支付方式
          this.ruleForm.F_Stock = res.F_Stock //出货仓库
          this.ruleForm.F_Score = res.F_UseScore //使用积分
          this.ruleForm.F_RecommendId = res.F_RecommendId//推荐人id
          this.ruleForm.F_RecommendName = res.F_RecommendName//推荐人名称
          this.ruleForm.F_Belong = res.F_Belong //归属人id
          this.ruleForm.F_BelongName = res.F_BelongName //归属人名称
          this.ruleForm.F_Remark = res.F_Remark //备注
          this.getAlreadyPoints(res.F_CustomerPhone)
        }
      });
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.order_form .form_select {
  width: 100%;
}
</style>
