<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" id="categorySet-add" @click="addCategory" :disabled="disabled">新增管辖品类</a-button>
        </div>
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.bizUserScopeSn"
          rowKeyName="bizUserScopeSn"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 产品分类 -->
          <template slot="classify" slot-scope="text,record,index">
            <div style="max-height:64px;overflow-y:scroll;">
              <a-row v-if="record.productTypeList && record.productTypeList.length>0">
                <a-col :span="20">
                  <a-tag
                    :id="'categorySet-chooseType'+record.bizUserScopeSn"
                    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;" :id="'categorySet-chooseType-btn'+record.bizUserScopeSn" @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;" :id="'categorySet-chooseType-btn1'+record.bizUserScopeSn" @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:64px;overflow-y:scroll;">
              <a-row v-if="record.productBrandList && record.productBrandList.length>0">
                <a-col :span="20">
                  <a-tag
                    :id="'categorySet-chooseBrand'+record.bizUserScopeSn"
                    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;" :id="'categorySet-chooseBrand-btn'+record.bizUserScopeSn" @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;" :id="'categorySet-chooseBrand-btn1'+record.bizUserScopeSn" @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"
              :id="'categorySet-delete-btn'+record.bizUserScopeSn"
              @click="handleDel(record)"
            >
              删除
            </a-button>
          </span>
        </s-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 { STable } from '@/components'
import ChooseBrandModal from './chooseBrandModal.vue'
import ChooseTypeModal from './chooseTypeModal.vue'
// 接口
import { getNewScopeSn, queryProductScopePage, saveProductBrandList, saveProductTypeList, bizuserScopeDelete, deleteProductBrand, deleteProductType } from '@/api/bizuser'
export default {
  name: 'CategorySet',
  mixins: [commonMixin],
  components: { ChooseBrandModal, ChooseTypeModal, STable },
  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' }
      ],
      // 查询参数
      queryParam: {
        hasDetail: 1
      },
      dataSource: [], // 列表数据
      openModal: false, //  新增编辑产品品牌  弹框
      itemSn: '', //  当前sn
      nowData: null, //  当前记录数据
      openBrandModal: false, // 打开品牌弹窗
      openTypeModal: false, // 打开分类弹窗
      chooseBrand: [], // 选择品牌数据
      chooseType: [], // 选择分类数据
      chooseObj: null, // 选择品牌 内容
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        this.queryParam.userSn = this.$route.query.sn
        this.queryParam.bizUserSn = this.bizUserSn
        // 获取列表数据  有分页
        return queryProductScopePage(Object.assign(parameter, this.queryParam)).then(res => {
          const data = res.data
          // 计算列表序号
          const no = (data.pageNo - 1) * data.pageSize
          this.total = data.count || 0
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
          }
          this.dataSource = data.list

          this.disabled = false
          this.spinning = false
          return data
        })
      }
    }
  },
  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.unshift(newData)
        }
        _this.spinning = false
        _this.disabled = false
      })
    },
    // 删除分类、品牌标签
    delLabel (bigRow, row, type) {
      const _this = this
      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) {
      this.chooseBrand = row.productBrandList
      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.$refs.table.refresh()
          }
        })
      } else if (type == 'CATEGORY') {
        ajaxdata.productTypeList = list
        saveProductTypeList(ajaxdata).then(res => {
          if (res.status == 200) {
            this.openTypeModal = false
            this.$refs.table.refresh()
          }
        })
      }
    },
    // 整行删除 删除
    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.$refs.table.refresh()
    },
    // 计算表格高度
    setTableH () {
      const addBtnHeight = this.$refs.categorySetAddBtn.offsetHeight
      this.tableHeight = window.innerHeight - addBtnHeight - 325
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
