<template>
  <div class="categorySet-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-card size="small" :bordered="false" class="categorySet-cont">
        <div class="table-operator" ref="categorySetAddBtn">
          <a-button type="primary" class="button-error" @click="addCategory" :disabled="disabled">+新增管辖品类</a-button>
        </div>
        <a-table
          bordered
          :data-source="dataSource"
          :columns="columns"
          ref="table"
          style="word-break: break-all;">
          <!-- :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ y: tableHeight }" -->
          <!-- 产品分类 -->
          <template slot="classify" slot-scope="text,record,index">
            <div style="max-height:230px;overflow-y:scroll;">
              <a-row v-if="record.productTypeList && record.productTypeList.length>0">
                <a-col :span="20">
                  <a-tag style="margin-bottom:10px;" closable @close.prevent="delLabel(record.bizUserScopeSn,con,'typeList')" v-for="(con,i) in record.productTypeList" :key="i">
                    {{ con.dataName }}
                  </a-tag>
                </a-col>
                <a-col :span="4" 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>
          </template>
          <!-- 产品品牌 -->
          <template slot="brand" slot-scope="text,record,index">
            <div style="max-height:230px;overflow-y:scroll;">
              <a-row v-if="record.productBrandList && record.productBrandList.length>0">
                <a-col :span="20">
                  <a-tag style="margin-bottom:10px;" closable @close.prevent="delLabel(record.bizUserScopeSn,item,'brandList')" v-for="(item,j) in record.productBrandList" :key="j">
                    {{ item.dataName }}
                  </a-tag>
                </a-col>
                <a-col :span="4" 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>
          </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>
      </a-card>
    </a-spin>
    <!-- 选择产品品牌 -->
    <chooseBrandModal :openModal="openBrandModal" :chooseData="chooseBrand" @close="openBrandModal=false" @ok="handleBrandOk" />
    <!-- 选择产品分类 -->
    <chooseTypeModal :openModal="openTypeModal" :chooseData="chooseType" @close="openTypeModal=false" @ok="handleTypeOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import ChooseBrandModal from '@/views/common/chooseBrandModal.vue'
import ChooseTypeModal from '@/views/common/chooseTypeModal.vue'
import { getNewScopeSn, bizuserScopeQueryPage, saveProductBrandList, saveProductTypeList, bizuserScopeDelete, deleteProductBrand, deleteProductType } from '@/api/bizuser'
export default {
  name: 'CategorySet',
  mixins: [commonMixin],
  components: { ChooseBrandModal, ChooseTypeModal },
  props: {
    bizUserSn: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '分类', dataIndex: 'no', width: '42%', align: 'center', scopedSlots: { customRender: 'classify' } },
        { title: '品牌', dataIndex: 'name', width: '42%', align: 'center', scopedSlots: { customRender: 'brand' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '16%', align: 'center' }
      ],
      dataSource: [],
      openModal: false, //  新增编辑产品品牌  弹框
      itemSn: '', //  当前sn
      nowData: null, //  当前记录数据
      openBrandModal: false,
      openTypeModal: false,
      chooseBrand: [],
      chooseType: [],
      chooseObj: null// 选择品牌 内容
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'powerUserList' })
    },
    // 新增管辖品类
    addCategory () {
      const _this = this
      _this.spinning = true
      _this.disabled = true
      getNewScopeSn({}).then(res => {
        if (res.status == 200) {
          const newData = {
            bizUserScopeSn: res.data,
            productTypeList: [],
            productBrandList: []
          }
          _this.dataSource.push(newData)
        }
        _this.spinning = false
        _this.disabled = false
      })
    },
    // 删除分类、品牌标签
    delLabel (bigRow, row, type) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要删除吗？',
        centered: true,
        onOk () {
          const bigPos = _this.dataSource.findIndex(con => { return bigRow == con.bizUserScopeSn })
          if (type == 'typeList') {
            const typePos = _this.dataSource[bigPos].productTypeList.findIndex(item => { return item.id == row.id })
            deleteProductType({ id: _this.dataSource[bigPos].productTypeList[typePos].id }).then(res => {
              if (res.status == 200) {
                _this.dataSource[bigPos].productTypeList.splice(typePos, 1)
              }
            })
          } else {
            const brandPos = _this.dataSource[bigPos].productBrandList.findIndex(obj => { return obj.id == row.id })
            deleteProductBrand({ id: _this.dataSource[bigPos].productBrandList[brandPos].id }).then(res => {
              if (res.status == 200) {
                _this.dataSource[bigPos].productBrandList.splice(brandPos, 1)
              }
            })
          }
        }
      })
    },
    // 添加分类标签
    addClassifyTag (pos, row) {
      const newData = []
      row.productTypeList.forEach(item => {
        const obj = {}
        obj.productTypeSn = item.dataSn
        obj.goodsSn = item.dataSn
        obj.productTypeName = item.dataName
        newData.push(obj)
      })
      this.chooseType = newData
      this.chooseObj = row
      this.openTypeModal = true
    },
    handleClassifyModal (con) {
      const chooseList = con
      this.openTypeModal = false
      this.dataSource[this.ChooseClassifyPos].productTypeList = [...this.dataSource[this.ChooseClassifyPos].productTypeList, ...chooseList]
    },
    // 分类
    handleTypeOk (obj) {
      this.chooseType = obj
      this.saveChangeData('CATEGORY')
    },
    // 添加品牌标签
    addBrandTag (pos, row) {
      const newData = []
      row.productBrandList.forEach(item => {
        const obj = {}
        obj.goodsSn = item.dataSn
        newData.push(obj)
      })
      this.chooseBrand = newData
      this.chooseObj = row
      this.openBrandModal = true
    },
    // 品牌
    handleBrandOk (obj) {
      this.chooseBrand = obj
      this.saveChangeData('BRAND')
    },
    saveChangeData (type) {
      const _this = this
      if (type == 'BRAND') { //  选择品牌
        if (_this.chooseBrand.length > 0) {
          const snList = []
          _this.chooseBrand.map(item => {
            const newObj = {}
            newObj.dataSn = item.brandSn
            snList.push(newObj)
          })
          this.save(snList, type)
        }
      } else if (type == 'CATEGORY') { //  选择分类
        if (_this.chooseType.length > 0) {
          const snList = []
          _this.chooseType.map(item => {
            const newObj = {}
            newObj.dataSn = item.productTypeSn
            snList.push(newObj)
          })
          this.save(snList, type)
        }
      }
    },
    save (list, type) {
      const ajaxdata = { userSn: this.$route.query.sn, bizUserScopeSn: this.chooseObj.bizUserScopeSn, bizUserSn: this.bizUserSn }
      if (type == 'BRAND') {
        ajaxdata.productBrandList = list
        saveProductBrandList(ajaxdata).then(res => {
          if (res.status == 200) {
            this.openBrandModal = false
            this.getTableData()
          }
        })
      } else if (type == 'CATEGORY') {
        ajaxdata.productTypeList = list
        saveProductTypeList(ajaxdata).then(res => {
          if (res.status == 200) {
            this.openTypeModal = false
            this.getTableData()
          }
        })
      }
    },
    // 整行删除 删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          bizuserScopeDelete({ id: row.bizUserScopeSn }).then(res => {
            if (res.status == 200) {
              const pos = _this.dataSource.findIndex(item => { return item.bizUserScopeSn == row.bizUserScopeSn })
              _this.dataSource.splice(pos, 1)
            }
          })
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.getTableData()
    },
    // 获取列表数据
    getTableData (params = {}) {
      this.spinning = true
      bizuserScopeQueryPage({
        pageNo: 1,
        pageSize: 20,
        userSn: this.$route.query.sn,
        hasDetail: 1,
        bizUserSn: this.bizUserSn,
        ...params
      }).then(res => {
        if (res.status == 200) {
          this.dataSource = res.data.list
        }
        this.spinning = false
      })
    },
    setTableH () {
      const addBtnHeight = this.$refs.categorySetAddBtn.offsetHeight
      this.tableHeight = window.innerHeight - addBtnHeight - 385
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .categorySet-wrap{
    .table-operator{
    text-align:right;
    }
  }
</style>
