<template>
  <div class="pages-wrap">
    <!-- 列表 -->
    <a-table
      class="sTable"
      style="margin-top:10px;width:100%;"
      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 style="max-height:126px;width:100%;overflow-y:scroll;" v-if="record.dataSourceOrigin=='0'">
          <a-row v-if="record.productTypeArr && record.productTypeArr.length>0">
            <a-col :span="17">
              <div v-for="con in record.productTypeArr" :key="con.id">
                <a-tooltip v-if="con.title&&con.title.length > 7" :title="con.title">
                  <a-tag style="margin-bottom:10px;" closable @close.prevent="delLabel(record.productScopeSn,con,'typeList')">
                    {{ `${con.title.slice(0, 7)}...` }}
                  </a-tag>
                </a-tooltip>
                <a-tag v-else style="margin-bottom:10px;" closable @close.prevent="delLabel(record.productScopeSn,con,'typeList')">
                  {{ con.title }}
                </a-tag>
              </div>
            </a-col>
            <a-col :span="6" style="text-align:right;">
              <a-tag style="background: #fff; borderStyle: dashed;" @click="addClassifyTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </a-col>
          </a-row>
          <a-row v-else>
            <a-col :span="24">
              <a-tag style="background: #fff; borderStyle: dashed;" @click="addClassifyTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </a-col>
          </a-row>
        </div>
        <span v-else v-for="con in record.productTypeArr" :key="con.id">{{ con.title }}</span>
      </template>
      <!-- 品牌 -->
      <template slot="productBrand" slot-scope="text, record,index">
        <div style="max-height:126px;overflow-y:scroll;" v-if="record.dataSourceOrigin=='0'">
          <a-row v-if="record.productBrandArr && record.productBrandArr.length>0">
            <a-col :span="17">
              <div v-for="item in record.productBrandArr" :key="item.brandSn">
                <a-tooltip v-if="item.brandName&&item.brandName.length > 7" :title="item.brandName">
                  <a-tag style="margin-bottom:10px;" closable @close.prevent="delLabel(record.productScopeSn,item,'brandList')">
                    {{ `${item.brandName.slice(0, 7)}...` }}
                  </a-tag>
                </a-tooltip>
                <a-tag v-else style="margin-bottom:10px;" closable @close.prevent="delLabel(record.productScopeSn,item,'brandList')">
                  {{ item.brandName }}
                </a-tag>
              </div>
            </a-col>

            <a-col :span="6" style="text-align:right;">
              <a-tag style="background: #fff; borderStyle: dashed;" @click="addBrandTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </a-col>
          </a-row>
          <a-row v-else>
            <a-col :span="24">
              <a-tag style="background: #fff; borderStyle: dashed;" @click="addBrandTag(index, record)" color="blue">
                <a-icon type="plus" />
              </a-tag>
            </a-col>
          </a-row>
        </div>
        <span v-else v-for="item in record.productBrandArr" :key="item.brandSn">{{ item.brandName }}</span>
      </template>
      <!-- 产品 -->
      <template slot="product" slot-scope="text, record">
        <span v-if="record.dataSourceOrigin=='1'" v-for="item in record.productThisList" :key="item.productSn">{{ item.productCode }}</span>
        <span v-else>--</span>
      </template>
      <!-- 省价特价 -->
      <template slot="provincePrice" slot-scope="text, record">
        <div v-if="record.dataSourceOrigin=='1'">
          <a-input-number
            size="small"
            style="width:90%;"
            v-model="record.provinceDiscountPrice"
            :min="0"
            :step="1"
            :precision="2"
            placeholder="请输入"
            :max="999999"
            @blur="e=>calculatePrice(e.target.value,record.productScopeSn,'province')"/>
        </div>
        <span v-else>--</span>
      </template>
      <!-- 省价折扣 -->
      <template slot="provinceDiscount" slot-scope="text, record">
        <div v-if="record.dataSourceOrigin=='0'">
          <a-input
            v-model="record.provinceDiscountRate"
            style="width:80%;"
            type="number"
            @input="record.provinceDiscountRate=record.provinceDiscountRate.match(/^\d{1,4}(\.?\d{0,2})/g) ? record.provinceDiscountRate.match(/^\d{1,4}(\.?\d{0,2})/g)[0] : ''"
            :min="0"
            placeholder="请输入"
            size="small"/>%
        </div>
        <span v-else>{{ (record.provinceDiscountRate||record.provinceDiscountRate==0)?record.provinceDiscountRate+'%':'--' }}</span>
      </template>
      <!-- 市价特价 -->
      <template slot="cityPrice" slot-scope="text, record">
        <div v-if="record.dataSourceOrigin=='1'">
          <a-input-number
            size="small"
            style="width:90%;"
            v-model="record.cityDiscountPrice"
            :min="0"
            :step="1"
            :precision="2"
            placeholder="请输入"
            :max="999999"
            @blur="e=>calculatePrice(e.target.value,record.productScopeSn,'city')"/>
        </div>
        <span v-else>--</span>
      </template>
      <!-- 市价折扣 -->
      <template slot="cityDiscount" slot-scope="text, record">
        <div v-if="record.dataSourceOrigin=='0'">
          <a-input
            v-model="record.cityDiscountRate"
            style="width:80%;"
            type="number"
            placeholder="请输入"
            @input="record.cityDiscountRate=record.cityDiscountRate.match(/^\d{1,4}(\.?\d{0,2})/g) ? record.cityDiscountRate.match(/^\d{1,4}(\.?\d{0,2})/g)[0] : ''"
            :min="0"
            size="small"/>%
        </div>
        <span v-else>{{ (record.cityDiscountRate||record.cityDiscountRate==0)?record.cityDiscountRate+'%':'--' }}</span>
      </template>
      <!-- 特约特价 -->
      <template slot="specialPrice" slot-scope="text, record">
        <div v-if="record.dataSourceOrigin=='1'">
          <a-input-number
            size="small"
            style="width:90%;"
            v-model="record.specialDiscountPrice"
            :min="0"
            :step="1"
            :precision="2"
            placeholder="请输入"
            :max="999999"
            @blur="e=>calculatePrice(e.target.value,record.productScopeSn,'special')"/>
        </div>
        <span v-else>--</span>
      </template>
      <!-- 特约折扣 -->
      <template slot="specialDiscount" slot-scope="text, record">
        <div v-if="record.dataSourceOrigin=='0'">
          <a-input
            v-model="record.specialDiscountRate"
            style="width:80%;"
            type="number"
            @input="record.specialDiscountRate=record.specialDiscountRate.match(/^\d{1,4}(\.?\d{0,2})/g) ? record.specialDiscountRate.match(/^\d{1,4}(\.?\d{0,2})/g)[0] : ''"
            :min="0"
            placeholder="请输入"
            step="0.01"
            size="small"/>%
        </div>
        <span v-else>{{ (record.specialDiscountRate||record.specialDiscountRate==0) ? record.specialDiscountRate+'%':'--' }}</span>
      </template>
      <!-- 设置起订量 -->
      <template slot="setNum" slot-scope="text, record">
        <v-select
          v-model="record.unitType"
          size="small"
          ref="returnReason"
          code="SCOPE_UNIT_TYPE"
          style="width:100%;"
          placeholder="请选择"
          allowClear></v-select>
        <a-input-number
          size="small"
          style="margin-top:8px;width:100%;"
          v-model="record.unitQty"
          :min="0"
          :step="1"
          :precision="0"
          :max="999999"
          placeholder="请输入"/>
      </template>
      <span slot="action" slot-scope="text,record">
        <a-button
          size="small"
          type="link"
          class="button-error"
          @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" />
  </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 { getNewScopeSn } from '@/api/promotion'
export default {
  name: 'TableType3',
  mixins: [commonMixin],
  components: { VSelect, ChooseBrandModal, ChooseTypeModal },
  props: {
    itemSn: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    const _this = this
    return {
      spinning: false,
      columns: [
        { title: '产品分类', width: '16%', scopedSlots: { customRender: 'productType' }, align: 'center' },
        { title: '品牌', width: '16%', scopedSlots: { customRender: 'productBrand' }, align: 'center' },
        { title: '产品', scopedSlots: { customRender: 'product' }, width: '10%', align: 'center' },
        { title: '省级原价', dataIndex: 'provincePrice', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '省级特价', scopedSlots: { customRender: 'provincePrice' }, width: '5%', align: 'center' },
        { title: '省级折扣', scopedSlots: { customRender: 'provinceDiscount' }, width: '5%', align: 'center' },
        { title: '市级原价', dataIndex: 'cityPrice', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '市级特价', scopedSlots: { customRender: 'cityPrice' }, width: '5%', align: 'center' },
        { title: '市级折扣', scopedSlots: { customRender: 'cityDiscount' }, width: '5%', align: 'center' },
        { title: '特约原价', dataIndex: 'specialPrice', width: '5%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '特约特价', scopedSlots: { customRender: 'specialPrice' }, width: '5%', align: 'center' },
        { title: '特约折扣', scopedSlots: { customRender: 'specialDiscount' }, width: '5%', align: 'center' },
        { title: '设置起订量', width: '7%', scopedSlots: { customRender: 'setNum' }, align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ],
      dataSource: [],
      openBrandModal: false,
      openTypeModal: false,
      chooseBrand: [],
      chooseType: [],
      val: '',
      brandTagIndex: null, // 所选品牌位置
      classifyTagIndex: null, // 所选分类位置
      dataSourceOrigin: 0 // 数据来源  1  选择产品  0 新增一行品类
    }
  },
  methods: {
    // 计算百分比
    calculatePrice (val, sn, typePrice) {
      const _this = this
      const pos = _this.dataSource.findIndex(con => con.productScopeSn == sn)
      const oldPrice = typePrice + 'Price'
      const str = ((val / _this.dataSource[pos][oldPrice]) * 100).toFixed(2)
      const name = typePrice + 'DiscountRate'
      _this.dataSource[pos][name] = str
      _this.$forceUpdate()
    },
    // 新增产品 数据
    setSourceData (list) {
      this.dataSource = this.dataSource.concat(list)
    },
    // 新增一行
    handleAddRow () {
      const _this = this
      _this.spinning = false
      getNewScopeSn({}).then(res => {
        if (res.status == 200) {
          const newData = {
            productScopeSn: res.data,
            dataSourceOrigin: '0',
            productTypeArr: [],
            productTypeList: [],
            productBrandArr: [],
            productBrandList: [],
            unitType: 'SL',
            unitQty: 1
          }
          _this.dataSource.push(newData)
        } else {
          _this.spinning = false
        }
      })
    },
    // 删除一行
    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.dataSourceOrigin === '0') {
          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.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.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
      _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.dataSourceOrigin === '0') {
          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
    },
    // 获取回显禁用数据
    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.dataSourceOrigin === '0') {
          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.dataSourceOrigin === '0') {
          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
    },
    handleEchoData (name, conArr) {
      conArr.map(item => {
        if (name === 'This') {
          item.code = item.productCode
          item.goodsSn = item.productSn
        } else {
          item.goodsSn = item['product' + name + 'Sn']
        }
      })
      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.dataSourceOrigin === '0') {
          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
    },
    // 关闭时清空表格数据
    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) => {
            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)
                }
              }
            })
          })
        }
      })
      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) => {
            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)
                }
              }
            })
          })
        }
      })
      return { list: c_brandArr, flag: flag, noTypeFlag: noTypeFlag }
    }
  }
}
</script>

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

</style>
