<template>
  <a-modal
    v-drag
    centered
    class="priceDifference-modal"
    :footer="null"
    :maskClosable="false"
    :title="title"
    v-model="isShow"
    @cancel="isShow=false"
    :width="960">
    <a-spin :spinning="spinning" tip="Loading...">
      <div style="min-height:100px;">
        <a-form-model
          id="priceDifference-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-form-model-item label="经销商名称">
            {{ detailData&&detailData.dealerName }}
          </a-form-model-item>
          <a-form-model-item label="上级经销商" required>
            <a-row :gutter="10">
              <a-col :span="17">
                <custList
                  id="priceDifference-custList"
                  v-if="!form.dealerUpsSn || isSpecial"
                  ref="custList"
                  :notDealerSn="notDealer"
                  :notDealerType="['SPECIAL']"
                  @change="custSupChange"
                  placeholder="请输入经销商名称搜索"></custList>
                <a-input id="priceDifference-superDealerName" v-else :value="superDealerName" disabled />
              </a-col>
              <a-col :span="4" v-if="!isSpecial">
                <a-input-number
                  :precision="2"
                  :min="0"
                  :max="100"
                  id="priceDifference-parentAllotRate"
                  v-model="parentAllotRate"
                  @change="rateSupChange"
                  placeholder="请输入比例"/> %
              </a-col>
              <a-col :span="2" v-if="!isSpecial && zdDealearList.length<3">
                <a-button
                  type="primary"
                  ghost
                  id="priceDifference-zdDealearList"
                  @click="addItem()"
                >添加指定</a-button>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item label="指定经销商" v-if="zdDealearList.length">
            <a-row :gutter="10" v-for="(item,index) in zdDealearList" :key="item.id">
              <a-col :span="17">
                <custList id="priceDifference-notZdDealer" :ref="'custList-'+item.id" :notDealerSn="notZdDealer" @change="(v,r)=>custChange(v,r,index)" placeholder="请输入经销商名称搜索"></custList>
              </a-col>
              <a-col :span="4">
                <a-input-number
                  :precision="2"
                  :min="0"
                  :max="100"
                  id="priceDifference-allotRate"
                  v-model="item.allotRate"
                  @change="(v)=>rateChange(v,index)"
                  placeholder="请输入比例"/> %
              </a-col>
              <a-col :span="2">
                <!-- <a-button
                  style="margin-right:5px;"
                  v-if="index==zdDealearList.length-1 && zdDealearList.length<3"
                  @click="addItem(item,index)"
                  title="添加"
                  size="small"
                  shape="circle"
                  icon="plus" /> -->
                <a-button
                  @click="delItem(item,index)"
                  type="primary"
                  title="删除"
                  size="small"
                  id="priceDifference-del"
                  shape="circle"
                  ghost
                  icon="minus"/>
              </a-col>
            </a-row>
          </a-form-model-item>
          <a-form-model-item label="箭冠总公司" v-if="!isSpecial">
            <a-row :gutter="10">
              <a-col :span="17">
                <a-input id="priceDifference-headOffice" value="箭冠总公司" disabled />
              </a-col>
              <a-col :span="4">
                <a-input-number
                  :precision="2"
                  :min="0"
                  :max="100"
                  id="priceDifference-hAllotRate"
                  v-model="hAllotRate"
                  @change="rateHChange"
                  placeholder="请输入比例"/> %
              </a-col>
            </a-row>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div style="padding:10px 10px 10px 40px;">
        <categoryTree v-if="showTable&&!isSpecial&&!form.dealerUpsSn" ref="categoryTree"></categoryTree>
      </div>
      <div class="btn-cont">
        <a-button id="priceDifference-cancel-btn" @click="isShow = false" style="font-size: 12px;">取消</a-button>
        <a-button
          type="primary"
          id="priceDifference-save-btn"
          style="margin-left: 20px;"
          @click="handleSave"
        >确定</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import custList from '@/views/common/custList.vue'
import { VSelect } from '@/components'
import categoryTree from './categoryTree'
// 接口
import { dealerUpsCreate, dealerUpsUpdate } from '@/api/dealer'
export default {
  name: 'PriceDiffModal',
  mixins: [commonMixin],
  components: { VSelect, custList, categoryTree },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      title: '差价设置', // 标题
      // 表单label布局设置
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 20 }
      },
      // 提交参数
      form: {
        dealerSn: undefined, // 经销商sn
        dealerUpsSn: undefined, // 上级经销商
        rebateParentType: [], // 差价归属
        rebateDealerList: [], // 经销商列表
        rebateScopeList: [] // 品类列表
      },
      parentAllotRate: '', // 上级经销商分配比例
      hAllotRate: '', // 总部分配比例
      // 表单规则验证
      rules: {
        rebateParentType: [{ required: true, message: '请选择差价归属方', trigger: 'change' }]
      },
      cjgsfList: [], // 箭冠总公司列表
      zdDealearList: [], // 指定经销商列表
      detailData: null, // 详情数据
      superDealerName: '', // 经销商数据
      checkedDealerSn: [], // 选中经销商sn
      showTable: false// 是否显示品牌分类列表
    }
  },
  computed: {
    // 是否是特约经销商
    isSpecial () {
      return this.detailData && this.detailData.dealerLevel == 'SPECIAL'
    },
    // 上级经销商数据
    notDealer () {
      return this.form.rebateDealerList.concat(this.zdDealearList).concat([{ 'parentDealerSn': this.form.dealerSn }])
    },
    // 指定经销商列表数据
    notZdDealer () {
      return this.form.rebateDealerList.concat(this.zdDealearList)
    }
  },
  methods: {
    // 新增
    setData (list, dealerSn, detail, checkedDealerSn) {
      this.detailData = detail
      this.form.dealerSn = dealerSn
      this.cjgsfList = list
      this.checkedDealerSn = checkedDealerSn
      // 如果当前经销商是特约经销商
      if (this.detailData.dealerLevel == 'SPECIAL') {
        // 默认只有上级经销商
        this.cjgsgChange(['SUPERIORS'])
      } else {
        this.cjgsgChange(['SUPERIORS', 'HEAD'])
      }
    },
    // 编辑
    editData (list, dealerSn, detail, row) {
      this.detailData = detail
      this.form.dealerSn = dealerSn
      this.form.dealerUpsSn = row.dealerUpsSn
      this.cjgsfList = list
      // 如果当前经销商是特约经销商
      if (this.detailData.dealerLevel == 'SPECIAL') {
        // 默认只有上级经销商
        this.form.rebateParentType = ['SUPERIORS']
      } else {
        this.form.rebateParentType = ['SUPERIORS', 'HEAD']
      }

      console.log(row)
      if (row) {
        row.rebateDealerList.map(item => {
          const row = {
            'id': item.id,
            'dealerSn': item.dealerSn,
            'parentDealerSn': item.parentDealerSn,
            'rebateParentType': item.rebateParentType,
            'dealerRelationSn': item.dealerRelationSn,
            'allotRate': Number(item.allotRate * 100).toFixed(2)
          }
          // 指定
          if (item.rebateParentType == 'ASSIGN') {
            this.zdDealearList.push(row)
            this.$nextTick(() => {
              this.$refs['custList-' + item.id][0].setDufaultVal(item.parentDealer.dealerName)
            })
          } else {
            // 上级和总部
            if (item.rebateParentType == 'SUPERIORS') {
              this.form.rebateDealerList[0] = row
              this.parentAllotRate = Number(item.allotRate * 100).toFixed(2)
              // 特约可编辑上级
              if (this.detailData.dealerLevel == 'SPECIAL') {
                this.$nextTick(() => {
                  this.$refs.custList.setDufaultVal(item.parentDealer.dealerName)
                })
              } else {
                // 其它不可编辑
                this.superDealerName = item.parentDealer.dealerName
              }
            } else {
              this.form.rebateDealerList[1] = row
              this.hAllotRate = Number(item.allotRate * 100).toFixed(2)
            }
          }
        })
      }
    },
    // 上级经销商修改
    custSupChange (val, row) {
      console.log(val, row)
      this.form.rebateDealerList[0]['parentDealerSn'] = val.key
      this.showTable = !!val.key
      if (!this.isSpecial) {
        this.$nextTick(() => {
          this.getCategoryList()
        })
      }
    },
    // 上级经销商 比例 change
    rateSupChange (val) {
      this.form.rebateDealerList[0]['allotRate'] = val
    },
    // 刷新品类列表
    getCategoryList () {
      const parentDealerSn = this.form.rebateDealerList[0]['parentDealerSn']
      if (parentDealerSn) {
        // 查询品类树
        this.$refs.categoryTree.pageInit(this.detailData, parentDealerSn, this.form.dealerSn)
      }
    },
    // 箭冠总公司  比例
    rateHChange (val) {
      this.form.rebateDealerList[1]['allotRate'] = val
    },
    // 指定经销商变更
    custChange (val, row, index) {
      console.log(val, index)
      this.zdDealearList[index]['parentDealerSn'] = val.key
    },
    // 指定经销商  比例
    rateChange (val, index) {
      console.log(val, index)
      this.zdDealearList[index]['allotRate'] = val
    },
    // 差价归属变更
    cjgsgChange (val) {
      console.log(val)
      this.form.rebateParentType = val
      // 指定经销商
      if (val.indexOf('ASSIGN') >= 0) {
        if (this.zdDealearList.length == 0) {
          this.addItem()
        }
      } else {
        this.zdDealearList = []
      }
      // 上级经销商
      if (val.indexOf('SUPERIORS') >= 0) {
        if (!this.form.rebateDealerList[0]) {
          this.form.rebateDealerList[0] = {
            'id': new Date().getTime(),
            'dealerSn': this.form.dealerSn,
            'parentDealerSn': undefined,
            'rebateParentType': 'SUPERIORS',
            'allotRate': 100
          }
          this.parentAllotRate = 100
        }
      } else {
        this.form.rebateDealerList[0] = null
        this.parentAllotRate = ''
      }
      // 总部经销商
      if (val.indexOf('HEAD') >= 0) {
        if (!this.form.rebateDealerList[1]) {
          this.form.rebateDealerList[1] = {
            'id': new Date().getTime() - 100,
            'dealerSn': this.form.dealerSn,
            'parentDealerSn': 1,
            'rebateParentType': 'HEAD',
            'allotRate': 0
          }
          this.hAllotRate = 0
        }
      } else {
        this.form.rebateDealerList[1] = null
        this.hAllotRate = ''
      }
    },
    // 增加指定经销商
    addItem (row, index) {
      const sn = new Date().getTime()
      this.zdDealearList.push({
        'id': sn,
        'dealerSn': this.form.dealerSn,
        'parentDealerSn': undefined,
        'rebateParentType': 'ASSIGN',
        'allotRate': ''
      })
    },
    // 删除指定经销商
    delItem (row, index) {
      const i = this.zdDealearList.findIndex(item => item.id == row.id)
      if (i >= 0) {
        this.zdDealearList.splice(i, 1)
      }
    },
    // 重置表单
    resetForm () {
      if (this.isSpecial || !this.form.dealerUpsSn) {
        this.$refs.custList.resetForm()
      }
      this.form.dealerSn = undefined
      this.form.dealerUpsSn = undefined
      this.form.rebateParentType = []
      this.form.rebateDealerList = []
      this.form.rebateScopeList = []
      this.zdDealearList = []
      this.hAllotRate = ''
      this.parentAllotRate = 100
      this.showTable = false
    },
    // 校验数据
    validateFormData (data) {
      let row
      let msg = ''
      for (let i = 0; i < data.length; i++) {
        row = data[i]
        if (row) {
          const rebateParentType = this.cjgsfList.find(item => item.code == row.rebateParentType)
          const type = rebateParentType ? rebateParentType.dispName : ''
          if (!row.parentDealerSn) {
            msg = '请选择' + type
            break
          }
          if (!row.allotRate && row.rebateParentType == 'ASSIGN') {
            msg = '请输入' + type + '的分配比例'
            break
          }
        }
      }
      return msg
    },
    // 保存
    handleSave () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(_this.form))
          formData.rebateDealerList = formData.rebateDealerList.concat(JSON.parse(JSON.stringify(this.zdDealearList)))
          console.log(formData)
          // 校验数据
          const errorMsg = this.validateFormData(formData.rebateDealerList)
          console.log(errorMsg)
          if (errorMsg) {
            _this.$message.error(errorMsg)
          } else {
            // 处理数据并校验比例之和是否100
            let pa = 0
            formData.rebateDealerList = formData.rebateDealerList.filter(item => item)
            formData.rebateDealerList.map(item => {
              item.allotRate = item.allotRate ? (item.allotRate / 100) : 0
              pa += item.allotRate
              delete item.id
            })
            console.log(formData)
            console.log(Number(pa).toFixed(2))
            if (Number(pa).toFixed(2) != 1) {
              _this.$message.error('差价比例之和必须是100%')
              return
            }

            if (!this.isSpecial && !this.form.dealerUpsSn) {
              formData.rebateScopeList = this.$refs.categoryTree.getResult()
              if (formData.rebateScopeList.length == 0) {
                _this.$message.error('请选择品类')
                return
              }
            }

            delete formData.rebateParentType

            // 提交数据
            _this.spinning = true
            const fun = this.form.dealerUpsSn ? dealerUpsUpdate : dealerUpsCreate
            fun(formData).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.isShow = false
                setTimeout(() => {
                  _this.$emit('ok')
                }, 100)
              }
              _this.spinning = false
            })
          }
        } else {
          return false
        }
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.resetForm()
        this.$emit('close')
      }
    }
  }
}
</script>

<style lang="less">
  .priceDifference-modal{
    .ant-modal-body {
      padding: 24px!important;
      .ant-input[disabled]{
        color:#666;
      }
    }
    .btn-cont {
      text-align: center;
      margin: 15px 0 10px;
    }
  }
</style>
