<template>
  <div class="pages-wrap">
    <!-- 列表 -->
    <a-table
      class="sTable"
      style="margin-top:10px;"
      ref="table"
      size="small"
      :pagination="false"
      :rowKey="(record) => record.productScopeSn"
      :columns="columns"
      :data-source="dataSource"
      bordered>
      <!-- 产品分类 -->
      <template slot="productType" slot-scope="text, record,index">
        <div v-if="!record.productThisList || record.productThisList.length==0">
          <div style="display: flex;align-items: center;" v-if="record.productTypeArr && record.productTypeArr.length>0">
            <div style="max-height:126px;overflow-y:auto;flex-grow: 1;display: flex;flex-wrap: wrap;" >
              <div v-for="con in record.productTypeArr" :key="con.id">
                <a-tooltip v-if="con.title&&con.title.length > 12" :title="con.title">
                  <a-tag style="margin-bottom:10px;" closable :id="'tableType-delType'+record.productScopeSn" @close.prevent="delLabel(record.productScopeSn,con,'typeList')">
                    {{ `${con.title.slice(0, 12)}...` }}
                  </a-tag>
                </a-tooltip>
                <a-tag v-else style="margin-bottom:10px;" :id="'tableType-delType'+record.productScopeSn" closable @close.prevent="delLabel(record.productScopeSn,con,'typeList')">
                  {{ con.title }}
                </a-tag>
              </div>
            </div>
            <div style="text-align:center;padding-left:10px;">
              <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加分类" :id="'tableType-addType'+record.productScopeSn" @click="addClassifyTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </div>
          </div>
          <div v-else>
            <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加分类" :id="'tableType-addType'+record.productScopeSn" @click="addClassifyTag(index, record)" color="blue">
              <a-icon type="plus" />
            </a-tag>
          </div>
        </div>
        <div v-else>
          <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加分类" :style="{color:'grey',cursor:'not-allowed'}">
            <a-icon type="plus" />
          </a-tag>
        </div>
      </template>
      <!-- 品牌 -->
      <template slot="productBrand" slot-scope="text, record,index">
        <div v-if="!record.productThisList || record.productThisList.length==0">
          <div style="display: flex;align-items: center;" v-if="record.productBrandArr && record.productBrandArr.length>0">
            <div style="max-height:126px;overflow-y:auto;flex-grow: 1;display: flex;flex-wrap: wrap;">
              <a-tag
                v-for="item in record.productBrandArr"
                :key="item.brandSn"
                style="margin-bottom:10px;"
                :id="'tableType-delBrand'+record.productScopeSn"
                closable
                @close.prevent="delLabel(record.productScopeSn,item,'brandList')">
                {{ item.brandName }}
              </a-tag>
            </div>
            <div style="text-align:center;padding-left:10px;">
              <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加品牌" :id="'tableType-addBrand'+record.productScopeSn" @click="addBrandTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </div>
          </div>
          <div v-else>
            <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加品牌" :id="'tableType-addBrand'+record.productScopeSn" @click="addBrandTag(index, record)" color="blue">
              <a-icon type="plus" />
            </a-tag>
          </div>
        </div>
        <div v-else>
          <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加品牌" :style="{color:'grey',cursor:'not-allowed'}">
            <a-icon type="plus" />
          </a-tag>
        </div>
      </template>
      <!-- 产品 -->
      <template slot="product" slot-scope="text, record,index">
        <div v-if="(record.productBrandArr && record.productBrandArr.length>0)||(record.productTypeArr && record.productTypeArr.length>0)">
          <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加产品" :style="{color:'grey',cursor:'not-allowed'}">
            <a-icon type="plus" />
          </a-tag>
        </div>
        <div v-else>
          <div style="display: flex;align-items: center;" v-if="record.productThisList && record.productThisList.length>0">
            <div style="max-height:126px;overflow-y:auto;flex-grow: 1;display: flex;flex-wrap: wrap;">
              <a-tag
                style="margin-bottom:10px;"
                closable
                :id="'tableType-delProduct'+record.productScopeSn"
                @close.prevent="delLabel(record.productScopeSn,item,'productList')"
                v-for="item in record.productThisList"
                :key="item.productSn">
                {{ item.productCode }}
              </a-tag>
            </div>
            <div style="text-align:center;padding-left:10px;">
              <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加产品" :id="'tableType-addProduct'+record.productScopeSn" @click="addProductTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </div>
          </div>
          <a-row v-else>
            <a-col :span="24">
              <a-tag style="background: #fff; borderStyle: dashed;cursor:pointer" title="添加产品" :id="'tableType-addProduct'+record.productScopeSn" @click="addProductTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </a-col>
          </a-row>
        </div>
      </template>
      <!-- 设置起订量 -->
      <template slot="setNum" slot-scope="text, record">
        <a-select
          default-value="SL"
          v-model="record.unitType"
          size="small"
          style="width:100%;"
          placeholder="请选择"
          :id="'tableType-unitType'+record.productScopeSn"
          allowClear>
          <a-select-option :value="con.code" v-for="con in unitTypeList" :key="con.id">
            {{ con.dispName }}
          </a-select-option>
        </a-select>
        <a-input-number
          size="small"
          style="margin-top:8px;width:100%;"
          v-model="record.unitQty"
          :id="'tableType-unitQty'+record.productScopeSn"
          :min="0"
          :step="1"
          :max="99999999"
          :precision="0"
          placeholder="请输入"/>
      </template>
      <span slot="action" slot-scope="text,record">
        <a-button
          size="small"
          type="link"
          class="button-error"
          :id="'tableType-del-btn'+record.productScopeSn"
          @click="handleDel(record)"
        >
          删除
        </a-button>
      </span>
    </a-table>
    <div class="btn-cont">
      <a-button id="tableType1-add" type="primary" class="button-gray" @click="handleAddRow">+新增一行</a-button>
    </div>
    <!-- 选择产品品牌 -->
    <chooseBrandModal
      pageType="1"
      ref="brandBox"
      :openModal="openBrandModal"
      :chooseData="chooseBrand"
      @close="openBrandModal=false"
      @ok="handleBrandOk" />
    <!-- 选择产品分类 -->
    <chooseTypeModal
      ref="typeBox"
      :openModal="openTypeModal"
      :linkageStatus="false"
      :chooseData="chooseType"
      @close="openTypeModal=false"
      @ok="handleTypeOk" />
    <!-- 选择产品 -->
    <chooseProductsModal
      type="dealership"
      ref="productBox"
      :openModal="openProductsModal"
      :chooseData="chooseProducts"
      @close="closeProductModal"
      @ok="handleProductsOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { VSelect } from '@/components'
import ChooseBrandModal from '@/views/common/chooseBrandModal.vue'
import ChooseTypeModal from '@/views/common/chooseTypeModal.vue'
import chooseProductsModal from './chooseProductsModal.vue'
export default {
  name: 'TableType1',
  mixins: [commonMixin],
  components: { VSelect, ChooseBrandModal, ChooseTypeModal, chooseProductsModal },
  props: {
    unitTypeList: { // 起订类型数据
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      spinning: false,
      columns: [
        { title: '产品分类', width: '35%', scopedSlots: { customRender: 'productType' }, align: 'center' },
        { title: '品牌', width: '25%', scopedSlots: { customRender: 'productBrand' }, align: 'center' },
        { title: '产品', width: '30%', scopedSlots: { customRender: 'product' }, align: 'center' },
        { title: '设置起订量', width: '7%', scopedSlots: { customRender: 'setNum' }, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '3%', align: 'center' }
      ],
      dataSource: [], // 列表数据
      openBrandModal: false, // 打开产品品牌弹窗
      openTypeModal: false, // 打开产品分类弹窗
      openProductsModal: false, // 打开产品弹窗
      chooseBrand: [], // 品牌数据
      chooseType: [], // 分类数据
      brandTagIndex: null, // 所选品牌位置
      classifyTagIndex: null, // 所选分类位置
      productTagIndex: null, // 所选产品位置
      chooseProducts: []// 所选产品数据
    }
  },
  methods: {
    // 关闭产品弹窗
    closeProductModal () {
      this.chooseProducts = []
      this.openProductsModal = false
    },
    // 生成随机数
    generateUniqueRandomNumber () {
      const timestamp = new Date().getTime()
      const randomNumber = Math.floor(Math.random() * 1e5).toString().padStart(5, '0')
      const uniqueRandomNumber = timestamp + randomNumber
      return uniqueRandomNumber
    },
    // 新增一行
    handleAddRow () {
      const _this = this
      const newSn = _this.generateUniqueRandomNumber()
      if (newSn) {
        const newData = {
          productScopeSn: newSn,
          productTypeArr: [],
          productTypeList: [],
          productBrandArr: [],
          productBrandList: [],
          productThisList: [],
          unitType: 'SL',
          unitQty: 1
        }
        _this.dataSource.push(newData)
      }
    },
    // 导入新增一行
    importRow (list) {
      const _this = this
      const dataList = _this.setShowData('This')
      const newList = list.filter(item => !dataList.some(con => con === item.product.productSn))
      if (newList.length > 0) {
        list.forEach(con => {
          const newSn = _this.generateUniqueRandomNumber()
          const newData = {
            productScopeSn: newSn,
            productThisList: [{
              productCode: con.productCode,
              productSn: con.product.productSn
            }],
            unitType: con.unitType,
            unitQty: con.unitQty
          }
          _this.dataSource.push(newData)
        })
      } else {
        _this.$message.warning('请勿导入重复数据！')
      }
    },
    // 删除一行
    handleDel (row) {
      const pos = this.dataSource.findIndex(con => con.productScopeSn == row.productScopeSn)
      this.dataSource.splice(pos, 1)
    },
    // 添加产品分类
    addClassifyTag (pos, row) {
      this.classifyTagIndex = pos
      this.openTypeModal = true
      this.chooseType = this.handleRowData(row)
      const getArr = this.setTypeShowData()
      // 无品牌有分类的选择数据
      const onlyTypeData = this.onlyType()
      // 获取品牌重复数据
      var flag = false
      var c_typeArr = []
      this.dataSource.forEach(item => {
        if ((item.productTypeArr && item.productTypeArr.length > 0) && (item.productBrandList && item.productBrandList.length > 0)) {
          item.productBrandList.forEach((con) => {
            row.productBrandList.forEach(newCon => {
              if (newCon.productBrandSn == con.productBrandSn) {
                flag = true
                c_typeArr = c_typeArr.concat(item.productTypeList)
              }
            })
          })
        }
      })
      const disTypeList = []
      getArr.forEach(con => {
        c_typeArr.forEach(item => {
          for (const i in item) {
            if (item[i] == con.goodsSn) {
              disTypeList.push(con)
            }
          }
        })
      })
      var uniqueArr = [...new Set(disTypeList)]

      if (row.productBrandArr && row.productBrandArr.length == 0) {
        this.$refs.typeBox.handleAllDisabled(onlyTypeData)
      } else {
        if (flag) {
          this.$refs.typeBox.handleAllDisabled(uniqueArr)
        } else {
          this.chooseType = []
          this.$refs.typeBox.handleAllDisabled([])
        }
      }
    },
    // 添加分类成功,重组数据
    handleTypeOk (mainArr) {
      const classifyArr = []
      const newClassifyArr = []
      mainArr.forEach(item => {
        if (item.productTypeLevel == 1) {
          if ((item.dataRef && !item.dataRef.children) || (!item.dataRef && !item.children)) {
            const objType1 = {
              productTypeSn1: item.snPaths
            }
            newClassifyArr.push(objType1)
            const obj = JSON.parse(JSON.stringify(objType1))
            obj.title = item.title
            obj.id = item.snPaths
            classifyArr.push(obj)
          }
        }
        if (item.productTypeLevel == 2) {
          if ((item.dataRef && !item.dataRef.children) || (!item.dataRef && !item.children)) {
            const typeArr1 = item.snPaths ? item.snPaths.split(',') : []
            const objType2 = {
              productTypeSn1: typeArr1[0],
              productTypeSn2: typeArr1[1]
            }
            newClassifyArr.push(objType2)
            const obj = JSON.parse(JSON.stringify(objType2))
            const newName = item.namePaths.split(',')
            obj.title = newName[1]
            obj.id = typeArr1[1]
            classifyArr.push(obj)
          }
        }
        if (item.productTypeLevel == 3) {
          const typeArr2 = item.snPaths ? item.snPaths.split(',') : []
          const objType3 = {
            productTypeSn1: typeArr2[0],
            productTypeSn2: typeArr2[1],
            productTypeSn3: typeArr2[2]
          }
          newClassifyArr.push(objType3)
          const obj = JSON.parse(JSON.stringify(objType3))
          const newName = item.namePaths.split(',')
          obj.title = newName[1] + '/' + newName[2]
          obj.id = typeArr2[2]
          classifyArr.push(obj)
        }
      })
      this.dataSource[this.classifyTagIndex].productTypeList = newClassifyArr
      this.dataSource[this.classifyTagIndex].productTypeArr = classifyArr
    },
    // 添加产品品牌
    addBrandTag (pos, row) {
      const _this = this
      _this.brandTagIndex = pos
      // 选中的所有品牌
      const dataList = _this.setShowData('Brand')
      _this.openBrandModal = true
      // 回显当前行选中
      const echoData = _this.handleEchoData('Brand', row.productBrandList)
      _this.chooseBrand = echoData
      // 只有品牌没有分类
      const onlyBrandData = this.onlyBrand()
      // 同行中分类是否与所选分类相同   已选分类
      var flag = false
      var c_brandArr = []
      this.dataSource.forEach(item => {
        if ((item.productTypeArr && item.productTypeArr.length > 0) && (item.productBrandList && item.productBrandList.length > 0)) {
          item.productTypeArr.forEach((con) => {
            row.productTypeArr.forEach(newCon => {
              if (newCon.id == con.id) {
                flag = true
                c_brandArr = c_brandArr.concat(item.productBrandList)
              }
            })
          })
        }
      })
      const reBrandArr = c_brandArr.map(list => {
        return list.productBrandSn
      })
      if (row.productTypeArr && row.productTypeArr.length == 0) {
        _this.$refs.brandBox.handleDisabled(onlyBrandData)
      } else {
        if (flag) { // 当前行有重复分类
          _this.$refs.brandBox.handleDisabled(reBrandArr)
        } else {
          _this.chooseBrand = []
          _this.$refs.brandBox.handleDisabled([])
        }
      }
    },
    // 添加品牌成功，重组数据
    handleBrandOk (conList) {
      const newConList = conList.map(con => {
        return {
          productBrandSn: con.brandSn
        }
      })
      this.dataSource[this.brandTagIndex].productBrandArr = conList
      this.dataSource[this.brandTagIndex].productBrandList = newConList
    },
    // 添加产品
    addProductTag (pos, row) {
      this.productTagIndex = pos
      const echoData = this.handleEchoData('This', row.productThisList)
      this.chooseProducts = echoData
      this.openProductsModal = true
      const dataList = this.setShowData('This')
      this.$refs.productBox.handleDisabled(dataList)
    },
    // 添加产品成功，重组数据
    handleProductsOk (arr) {
      const newArr = []
      arr.forEach(item => {
        const obj = {
          productCode: item.code,
          productSn: item.productSn
        }
        newArr.push(obj)
      })
      this.dataSource[this.productTagIndex].productThisList = newArr
    },
    // 获取回显禁用数据
    setShowData (name) {
      const _this = this
      const snArr = []
      _this.dataSource.forEach(item => {
        if (item['product' + name + 'List'] && item['product' + name + 'List'].length > 0) {
          item['product' + name + 'List'].forEach(con => {
            const newName = name === 'This' ? '' : name
            snArr.push(con['product' + newName + 'Sn'])
          })
        }
      })
      return snArr
    },
    // 只有分类
    onlyType (name, onlyName) {
      const _this = this
      const snArr = []
      _this.dataSource.forEach(item => {
        if (item.productTypeList && item.productTypeList.length > 0) {
          if (!item.productBrandList || (item.productBrandList && item.productBrandList.length == 0)) {
            item.productTypeList.forEach(con => {
              for (const i in con) {
                const newObj = {
                  goodsSn: con[i]
                }
                if (i === 'productTypeSn1') {
                  newObj.disabled = true
                } else {
                  newObj.disableCheckbox = true
                }
                snArr.push(newObj)
              }
            })
          }
        }
      })
      return snArr
    },
    // 只有品牌
    onlyBrand () {
      const _this = this
      var snArr = []
      _this.dataSource.forEach(item => {
        if (item.productBrandList && item.productBrandList.length > 0) {
          if (!item.productTypeArr || (item.productTypeArr && item.productTypeArr.length == 0)) {
            item.productBrandList.forEach(con => {
              snArr.push(con.productBrandSn)
            })
          }
        }
      })
      return snArr
    },
    // 筛选code和goodsSn值
    handleEchoData (name, conArr) {
      if (conArr) {
        conArr.map(item => {
          if (name === 'This') {
            item.code = item.productCode
            item.goodsSn = item.productSn
          } else {
            item.goodsSn = item['product' + name + 'Sn']
          }
        })
      } else {
        conArr = []
      }
      return conArr
    },
    // 灰选已选分类
    handleRowData (row) {
      const echoData = []
      row.productTypeList.forEach(item => {
        for (const i in item) {
          const newObj = {
            goodsSn: item[i]
          }
          if (i === 'productTypeSn1') {
            newObj.disabled = true
          } else {
            newObj.disableCheckbox = true
          }
          echoData.push(newObj)
        }
      })
      return echoData
    },
    // 禁用行中产品品牌或者产品数据
    setTypeShowData () {
      const _this = this
      const snArr = []
      _this.dataSource.forEach(item => {
        if (item.productTypeList && item.productTypeList.length > 0) {
          item.productTypeList.forEach(con => {
            for (const i in con) {
              const newObj = {
                goodsSn: con[i]
              }
              if (i === 'productTypeSn1') {
                newObj.disabled = true
              } else {
                newObj.disableCheckbox = true
              }
              snArr.push(newObj)
            }
          })
        }
      })
      return snArr
    },
    // 获取表格数据
    getResultVal () {
      const resultObj = JSON.parse(JSON.stringify(this.dataSource))
      resultObj.map(item => {
        delete item.productTypeArr
        delete item.productBrandArr
        return item
      })
      return resultObj
    },
    // 表格数据赋值
    setTabVal (formData) {
      this.dataSource = formData
    },
    // 关闭时清空表格数据
    reSetTableData () {
      this.dataSource = []
    },
    // 删除标签
    delLabel (sn, row, type) {
      const pos = this.dataSource.findIndex(con => con.productScopeSn == sn)
      if (type === 'typeList') {
        // 判断品牌是否有重复 重复值有无分类
        const isRepeatBrandFlag = this.isRepeatBrand(this.dataSource[pos])
        const uniqueArr1 = this.dataSource[pos].productTypeList && this.dataSource[pos].productTypeList.length > 0 ? this.dataSource[pos].productTypeList : []
        if (isRepeatBrandFlag.flag && isRepeatBrandFlag.noTypeFlag && uniqueArr1.length == 1) {
          this.dataSource.splice(pos, 1)
        } else {
          const i = this.dataSource[pos].productTypeArr.findIndex(con => con.id == row.id)
          this.dataSource[pos].productTypeArr.splice(i, 1)
          this.dataSource[pos].productTypeList.splice(i, 1)
        }
      } else if (type === 'brandList') {
        const isRepeatTypeFlag = this.isRepeatType(this.dataSource[pos])
        const uniqueArr = this.dataSource[pos].productBrandList && this.dataSource[pos].productBrandList.length > 0 ? this.dataSource[pos].productBrandList : []
        if (isRepeatTypeFlag.flag && isRepeatTypeFlag.noTypeFlag && uniqueArr.length == 1) {
          this.dataSource.splice(pos, 1)
        } else {
          const j = this.dataSource[pos].productBrandArr.findIndex(con => con.brandSn == row.brandSn)
          this.dataSource[pos].productBrandArr.splice(j, 1)
          this.dataSource[pos].productBrandList.splice(j, 1)
        }
      } else {
        const k = this.dataSource[pos].productThisList.findIndex(con => con.productSn == row.productSn)
        this.dataSource[pos].productThisList.splice(k, 1)
      }
      this.$forceUpdate()
    },
    // 判断当前行是否有重复品牌
    isRepeatBrand (row) {
      var flag = false
      var noTypeFlag = false
      var c_typeArr = []
      this.dataSource.forEach(item => {
        if (item.productBrandList && item.productBrandList.length > 0) {
          item.productBrandList.forEach((con) => {
            if (row.productBrandList && row.productBrandList.length > 0) {
              row.productBrandList.forEach(newCon => {
                if (newCon.productBrandSn == con.productBrandSn) {
                  flag = true
                  if (item.productTypeList && item.productTypeList.length == 0) {
                    noTypeFlag = true
                  } else {
                    c_typeArr = c_typeArr.concat(item.productTypeList)
                  }
                }
              })
            } else {
              flag = false
            }
          })
        }
      })
      return { list: c_typeArr, flag: flag, noTypeFlag: noTypeFlag }
    },
    // 判断分类是否重复
    isRepeatType (row) {
      var flag = false
      var noTypeFlag = false
      var c_brandArr = []
      this.dataSource.forEach(item => {
        if (item.productTypeArr && item.productTypeArr.length > 0) {
          item.productTypeArr.forEach((con) => {
            if (row.productTypeArr && row.productTypeArr.length > 0) {
              row.productTypeArr.forEach(newCon => {
                if (newCon.id == con.id) {
                  flag = true
                  if (item.productBrandList && item.productBrandList.length == 0) {
                    noTypeFlag = true
                  } else {
                    c_brandArr = c_brandArr.concat(item.productBrandList)
                  }
                }
              })
            } else {
              flag = false
            }
          })
        }
      })
      return { list: c_brandArr, flag: flag, noTypeFlag: noTypeFlag }
    }
  }
}
</script>

<style lang="less" scoped>
  .pages-wrap{
    .btn-cont {
      text-align: center;
      margin: 10px 0;
    }
  }

</style>
