<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="请输入手机号码"/>
          </el-form-item>
        </el-col>
        <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_TrackingNo" placeholder="请输入快递单号"/>
          </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="请输入收件人手机号"/>
          </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="请输入邮编"/>
          </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-input v-model="ruleForm.F_ExpressFee" placeholder="请输入运费"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式" >
            <el-input v-model="ruleForm.F_PayType" placeholder="请输入支付方式"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收金额" >
            <el-input v-model="ruleForm.F_RealPrice" placeholder="请输入实收金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用积分" >
            <el-input v-model="ruleForm.F_Score" placeholder="请输入使用积分"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联会员ID" >
            <el-input v-model="ruleForm.F_VipId" placeholder="请输入关联会员ID"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span='8'>
          <el-form-item label="商品分类" >
            <el-select v-model="commoditySearchData.className" placeholder="请选择商品分类" class="filter-item" clearable value-key="F_ClassId" @change="commodityTypeChange">
              <el-option
                v-for="item in commodityTypeLists"
                :key="item.F_ClassId"
                :label="item.F_ClassName"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='8'>
          <el-form-item label="商品" prop="productName" >
            <el-select v-model="commoditySearchData.productName" class="filter-item" value-key="F_ProductId" clearable placeholder="请选择订单类型" @change="commodityListChange">
              <el-option
                v-for="item in commodityListLists"
                :key="item.F_ProductId"
                :label="item.F_ProductName"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='8'>
          <el-form-item label="商品数量" >
            <el-input-number v-model="commoditySearchData.num" :min="1" label="描述文字"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" @click="addCommodity">添加商品</el-button>
        <el-button type="primary" @click="getActivityAccountList">获取优惠</el-button>
      </el-form-item>
      <el-form-item label="商品">
        <el-table :data="commodityTableData" stripe style="width: 100%">
          <el-table-column prop="F_ProductName" label="商品名称" width="180"></el-table-column>
          <el-table-column prop="F_Count" label="商品数量" width="180"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="btn_deleteCommodity(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="优惠">
        <el-table :data="activityAccountData" stripe style="width: 100%" @selection-change="activityAccountSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="活动类型" width="180">
            <template slot-scope="scope">
              {{ scope.row.type | activityAccountTypeFilter }}
            </template>
          </el-table-column>
          <el-table-column prop="money" label="优惠金额" width="180"></el-table-column>
          <el-table-column prop="gift" label="赠品"></el-table-column>
        </el-table>
      </el-form-item>
      <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, editOrder, getActivityAccount } from "@/api/orderManagement/orderList";
import { validateTel } from '@/utils/validate'
import { delFiles, filterContent, pickerOptions } from '@/utils'
import { getCommodityType } from '@/api/commodityManagement/commodityType'
import { getCommodityList } from '@/api/commodityManagement/commodityList'
import { getAreaTreeChildNode } from '@/api/systemSetup/roleSetting/areaManagement'



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: {
    activityAccountTypeFilter(status) {
      const statusMap = {
        1: '满赠',
        2: '生日',
        3: '满减',
        4: '特惠',
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      provinceDatas: [], // 省下拉数据
      cityDatas: [], //市下拉数据
      areaDatas: [], //区/县下拉数据
      townDatas: [], //乡镇/下拉数据
      stockList: [], //出库货仓下拉数据
      expressList: [], //快递
      commodityTypeLists: [], //商品分类下拉数据
      commodityListLists: [], //商品下拉数据
      commoditySearchData: { //商品搜索数据
        classId: '', // 商品分类id
        className: '', // 商品分类名称
        productName: '', //商品名称
        productId: '', //商品id
        num: 1, //商品数量
      },
      commodityTableData: [], //添加商品
      activityAccountData: [], //活动核算数据
      orderType: [],//订单类型
      pickerOptions, // 日期数据

      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: '', //否 number 运费
        F_PayType: '', //否 string  支付方式
        F_Stock: '', //否 string 出货仓库
        F_RealPrice: '', //否 number 实收金额
        F_VipId: '', //否 number 关联会员id
        F_Score: '', //否 number  使用积分
      },
      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: 'blur',
          message: '请输入订单类型',
        }],
        F_Id: [{
          required: true,
          trigger: 'blur',
          message: '请输入订单号',
        }],
      },
      loading: false
    };
  },
  created() {
    this.getCommodityTypeSelect()
    this.getStock()
    this.getOrderType()
    this.getExpress()
    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.OrderDetailList = this.ruleForm.OrderDetailList === this.commodityTableData ? [] : this.commodityTableData
          this.ruleForm.F_ExpressFee = this.ruleForm.F_ExpressFee == '' ? 0 : this.ruleForm.F_ExpressFee
          this.ruleForm.F_RealPrice = this.ruleForm.F_RealPrice == '' ? 0 : this.ruleForm.F_RealPrice
          this.ruleForm.F_VipId = this.ruleForm.F_VipId == '' ? 0 : this.ruleForm.F_VipId
          this.ruleForm.F_Score = this.ruleForm.F_Score == '' ? 0 : this.ruleForm.F_Score
          // 编辑
          editOrder(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
          }
        })
      })
    },
    //获取商品分类
    getCommodityTypeSelect() {
      this.loading = true
      return new Promise(resolve => {
        const data = {
          pageindex: 1, // int 第几页
          pagesize: 300, // int 每页几条信息
          ParentId: 0,
        }
        getCommodityType(data).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.commodityTypeLists = response.data.Rows
          }
        })
        resolve()
      })
    },
    //获取商品
    getCommodityListSelect() {
      this.loading = true
      return new Promise(resolve => {
        const params = {
          pageindex: 1, // int 第几页,
          pagesize: 300, // int 每页几条信息,
          ProductId: '',
          ClassId: this.commoditySearchData.classId === '' ? 0 : this.commoditySearchData.classId,
          ClassName: this.commoditySearchData.className,
          ProductName: '',
          PinyinShort: '',
          ProductNumber: '',
          ProductShortName: '',
          tag: '',
          issale: 1,
        }
        getCommodityList(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.commodityListLists = response.data.Rows
          }
        })
        resolve()
      })
    },
    commodityTypeChange(item) {
      this.commoditySearchData.classId = item.F_ClassId
      this.commoditySearchData.className = item.F_ClassName
      this.getCommodityListSelect()
    },
    commodityListChange(item) {
      this.commoditySearchData.productId = item.F_ProductId
      this.commoditySearchData.productName = item.F_ProductName
    },
    addCommodity() {
      if (this.commoditySearchData.productName === ''){
        this.$message({
          message: '请选择商品！',
          type: 'warning'
        })
        return
      }
      let data = {
        F_ProductId: this.commoditySearchData.productId,
        F_ProductName: this.commoditySearchData.productName,
        F_Count: this.commoditySearchData.num,
      }
      this.commodityTableData.push(data)
    },
    //获取活动核算
    getActivityAccountList() {
      return new Promise(resolve => {
        const params = this.commodityTableData
        getActivityAccount(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            if (response.data.length === 0) {
              this.$message({
                message: '没有优惠！',
                type: 'warning'
              })
            } else {
              this.activityAccountData = response.data
            }
          }
        })
        resolve()
      })
    },
    //删除商品
    btn_deleteCommodity (val) {
      let index = this.commodityTableData.indexOf(val)
      this.commodityTableData.splice(index, 1)
    },
    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.ruleForm.OrderDetailList = res.OrderDetailList //订单详情list
          this.commodityTableData = res.OrderDetailList
          this.ruleForm.UseActList = res.UseActList //活动详情list
          this.activityAccountData = res.UseActList
          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_RealPrice = res.F_RealPrice == 0 ? '' : res.F_RealPrice //实收金额
          this.ruleForm.F_VipId = res.F_VipId == 0 ? '' : res.F_VipId //关联会员id
          this.ruleForm.F_Score = res.F_Score ==0 ? '' : res.F_Score //使用积分
        }
      });
    },
  }
};
</script>

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