<template>
  <a-modal
    centered
    class="chooseType-modal"
    :footer="null"
    :maskClosable="false"
    title="选择品类"
    v-model="isShow"
    @cancel="isShow=false"
    :width="960">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        id="chooseType-form"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-form-model-item label="价格级别" prop="priceLevel">
          <v-select
            code="PRICE_LEVEL"
            :notIn="notArr"
            style="width: 70%;"
            id="chooseType-level"
            v-model="form.priceLevel"
            allowClear
            :disabled="notArrFlag"
            placeholder="请选择价格级别"></v-select>
        </a-form-model-item>
        <a-form-model-item label="添加品类" prop="typeVal">
          <span v-for="(con,i) in filterList" :key="con.id" >
            <a-checkbox id="chooseType-typeVal" :checked="con.checked" @change="e=>onChangeType(e.target.checked,i)" v-show="con.id!=4">
              {{ con.name }}
            </a-checkbox>
            <a-checkbox id="chooseType-typeVal1" :checked="con.checked" @change="e=>onChangeType(e.target.checked,i)" v-show="con.id==4&&disabledList.length==0">
              <a-tooltip placement="rightTop">
                <template slot="title">
                  <span>选择全品类后，未来新加入的品类也将自动默认为已选择状态，无需再次手动操作。</span>
                </template>
                <span>{{ con.name }}</span>
                <a-icon type="question-circle" style="margin-left:5px;" />
              </a-tooltip>
            </a-checkbox>
          </span>
        </a-form-model-item>
        <div class="typeListBox" v-show="form.typeVal!=4">
          <a-tree
            v-model="checkedList"
            checkable
            id="chooseType-typeListBox"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :replaceFields="replaceObj"
            :checkStrictly="true"
            @check="onCheck"
          />
        </div>
      </a-form-model>
      <div class="btn-cont">
        <a-button id="chooseType-modal-back" @click="isShow = false" >取消</a-button>
        <a-button type="primary" style="margin-left: 15px;" id="chooseType-modal-save" @click="handleSave">保存</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
// 组件
import { VSelect } from '@/components'
// 接口
import { dealerScopeCreate, queryWaitingData, dealerScopeQueryList } from '@/api/dealerScope'
export default {
  name: 'ChooseTypeModal',
  components: { VSelect },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      // label 标签布局
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 20 }
      },
      form: {
        priceLevel: undefined, // 价格级别
        typeVal: '0'// 产品品类
      },
      rules: {// 表单验证规则
        priceLevel: [
          { required: true, message: '请选择价格级别', trigger: 'change' }
        ],
        typeVal: [
          { required: true, message: '请选择产品品类', trigger: 'change' }
        ]
      },
      notArr: [], // 特约经销商  禁用选择
      notArrFlag: false, // 价格级别禁用状态
      treeData: [], // 品牌分类数据
      checkedList: [], // 已选产品分类
      autoExpandParent: false, // 是否自动展开父节点
      replaceObj: {// 替换 treeNode 中 对应字段
        children: 'sonList', title: 'name', key: 'sn'
      },
      disabledList: [], // 已选过禁用调的品类数据
      // 选择数据方式
      filterList: [{ id: '1', name: '全选', checked: false }, { id: '2', name: '自主品牌', checked: false }, { id: '3', name: '代理品牌', checked: false }, { id: '4', name: '全品类', checked: false }],
      allBarndSnList: [], // 全选分类数据
      ownBarndSnList: [], // 自主品牌分类数据
      agentBarndSnList: []// 代理品牌分类数据
    }
  },
  methods: {
    // 添加品类
    onChangeType (val, pos) {
      this.filterList.map(item => item.checked = false)
      this.filterList[pos].checked = val
      // 选择全品类   隐藏选择品类数据
      this.form.typeVal = '0'
      if (pos === 3 && val) {
        this.form.typeVal = this.filterList[pos].id
      }
      this.checkedList = []
      // 全选
      if (pos === 0 && val) {
        this.checkedList = this.allBarndSnList
      }
      // 自主
      if (pos === 1 && val) {
        this.checkedList = this.ownBarndSnList
      }
      if (pos === 2 && val) {
        this.checkedList = this.agentBarndSnList
      }
    },
    // 获取品牌sn
    getLevel1Data () {
      // 全选
      const allBarndSn = []; const ownBarndSn = []; const agentBarndSn = []
      this.treeData.forEach(con => {
        allBarndSn.push(con.sn)
        if (con.productBrandType === '1') {
          ownBarndSn.push(con.sn)
        }
        if (con.productBrandType === '2') {
          agentBarndSn.push(con.sn)
        }
      })
      // 全选
      this.allBarndSnList = allBarndSn
      // 自主品牌
      this.ownBarndSnList = ownBarndSn
      // 代理品牌
      this.agentBarndSnList = agentBarndSn
    },
    //  保存
    handleSave () {
      const _this = this
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(_this.form))
          if (formData.typeVal != '4') {
            let checkedArr = _this.changeCheckedList()
            if (checkedArr.length == 0) {
              _this.$message.warning('请添加品类！')
              return
            }
            // 全选时，过滤有禁用的已选过得品牌
            if (_this.disabledList.length > 0) {
              checkedArr = checkedArr.filter(items => {
                if (!_this.disabledList.includes(items)) return items
              })
              if (checkedArr.length == 0) {
                _this.$message.warning('勾选的品牌已存在，请重新勾选！！')
                return
              }
            }
            // 重组 后台所需要的数据结构
            const arr = []
            checkedArr.forEach(item => {
              const newArr = item.split('_')
              arr.push({
                productBrandSn: newArr[2],
                productTypeSn1: newArr[4] ? newArr[4] : undefined,
                productTypeSn2: newArr[6] ? newArr[6] : undefined,
                productTypeSn3: newArr[8] ? newArr[8] : undefined
              })
            })
            formData.scopeList = arr
          } else {
            formData.scopeList = []
          }
          formData.dealerSn = _this.$route.params.sn
          _this.spinning = true
          delete formData.typeVal
          dealerScopeCreate(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$emit('ok')
              _this.isShow = false
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 获取已选择的品类
    getDataList () {
      const _this = this
      queryWaitingData({}).then(res => {
        if (res.status == 200) {
          if (_this.disabledList && _this.disabledList.length > 0) {
            const newTreeData = _this.resetDisabledList(res.data, _this.disabledList)
            _this.treeData = newTreeData
          } else {
            _this.treeData = res.data
          }
          _this.getLevel1Data()
        }
        _this.spinning = false
      })
    },
    // 重组已选择数据，禁用已选择数据
    async getDisabledList () {
      const res = await dealerScopeQueryList({ dealerSn: this.$route.params.sn })
      // 重组数据
      if (res.status === '200') {
        const disabledList = res.data.map(item => {
          return '-1_1_' + item.productBrandSn + (item.productTypeSn1 ? '_2_' + item.productTypeSn1 : '') + (item.productTypeSn2 ? '_3_' + item.productTypeSn2 : '') + (item.productTypeSn3 ? '_4_' + item.productTypeSn3 : '')
        })
        this.disabledList = disabledList
        this.getDataList()
      }
    },
    // 遍历树，添加disabled属性
    resetDisabledList (tree, arr) {
      // 遍历树节点
      function traverse (node) {
        // 检查当前节点的 key 是否在 arr 中
        if (arr.includes(node.sn)) {
          // 如果在，则添加 disabled 属性
          node.disabled = true
        }
        // 如果节点有子节点，则递归遍历子节点
        if (node.sonList) {
          node.sonList.forEach(child => traverse(child))
        }
      }
      // 从树的根节点开始遍历
      tree.forEach(node => traverse(node))
      // 返回修改后的树
      return tree
    },
    // 点击复选框触发事件
    onCheck (checkedKeys) {
      this.checkedList = checkedKeys.checked
      this.filterList[0].checked = this.checkedList.length === this.allBarndSnList.length
      this.filterList[1].checked = this.checkedList.length === this.ownBarndSnList.length
      this.filterList[2].checked = this.checkedList.length === this.agentBarndSnList.length
    },
    // 重组选中数据
    changeCheckedList () {
      const ret = []
      this.checkedList.forEach((item, index) => {
        var flag = true
        this.checkedList.forEach(con => {
          if (con.includes(item + '_')) {
            flag = false
          }
        })
        if (flag) {
          ret.push(item)
        }
      })

      return ret
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$refs.ruleForm.resetFields()
        this.checkedList = []
        this.filterList.map(item => item.checked = false)
        this.$emit('close')
      } else {
        // 特约经销商   价格级别不能修改  省、市经销商时，不能选择特约价
        if (this.$route.params.dealerLevel === 'SPECIAL') {
          this.form.priceLevel = 'SPECIAL'
          this.notArrFlag = true
        } else {
          this.notArr = ['SPECIAL']
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .chooseType-modal{
    .typeListBox{
      padding:0 30px;
      max-height: 500px;
      overflow-y:scroll;
    }
    .ant-modal-body {
      padding: 40px 40px 24px;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }
  .has-error .ant-form-explain, .has-error .ant-form-split{
    margin-top:9px;
  }
  .ant-tree{
    display:flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  /deep/.ant-tree li{
    width: 33% !important;
  }
</style>
