<template>
  <div class="categoryList-wrap" :style="{minHeight:maxHeight+'px'}">
    <a-spin :spinning="spinning" tip="Loading...">
      <ve-table
        border-y
        v-show="!showEmpty"
        :scroll-width="0"
        :row-style-option="{clickHighlight: true}"
        :cellSelectionOption="{enable: false}"
        :virtual-scroll-option="{enable: false}"
        :columns="columns"
        :table-data="list"
        row-key-field-name="id"
        :expand-option="expandOption"
      />
      <div v-show="showEmpty" class="empty-data" :style="{height:maxHeight+'px'}"><a-empty description="暂无数据" :image="simpleImage"/></div>
    </a-spin>

  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { Empty } from 'ant-design-vue'
// 组件
import { VSelect } from '@/components'
// 接口
import { dealerUpsList, dealerUpsDelete } from '@/api/dealer'
// 子表格
const ChildTableComp = {
  name: 'ChildTableComp',
  template: `
        <div class="child-table-comp">
            <ve-table
              v-if="row.childData.length>0"
              :row-style-option="{clickHighlight: true, stripe: true}"
              :cellSelectionOption="{enable: false}"
              :scroll-width="0"
              :max-height="row.childData.length*30>300?300:row.childData.length*30+31"
              row-key-field-name="id"
              :virtual-scroll-option="{enable: true}"
              :columns="columns"
              :table-data="row.childData"
            />
            <a-empty v-else description="暂无品类" :image="simpleImage"/>
        </div>
    `,
  props: {
    row: Object
  },
  data () {
    return {
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 为空 图片地址
      columns: [
        { title: '序号', field: 'no', key: 'a', width: 40, align: 'center', operationColumn: false },
        { title: '品牌', field: 'productBrandName', key: 'b', width: 100, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '一级分类', field: 'productTypeName1', key: 'e', width: 180, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '二级分类', field: 'productTypeName2', width: 180, key: 'i', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '三级分类', field: 'productTypeName3', width: 180, key: 'm', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } }
      ]
    }
  }
}
export default {
  name: 'DetailProductList',
  mixins: [commonMixin],
  components: { VSelect },
  props: {
    newLoading: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: [String, Number],
      default: '300'
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      dataSource: [], // 列表数据
      list: [], // 重组后适合的列表数据
      tableHeight: this.maxHeight, // 表格高度
      columnWidthResizeOption: {// 表格列宽设置
        // default false
        enable: true,
        // column resize min width
        minWidth: 50
      },
      expandOption: {
        defaultExpandAllRows: false,
        expandedRowKeys: [],
        render: ({ row, column, rowIndex }, h) => {
          return <ChildTableComp row={row} />
        },
        // 重新赋值处理
        afterExpandRowChange: ({ afterExpandedRowKeys, row, rowIndex }) => {
          this.changeExpandedRowKeys(afterExpandedRowKeys)
        }
      },
      showEmpty: true, // 是否显示空页面
      checkedDealerSn: [], // 选中的经销商sn集合
      isTeyue: false// 是否显示删除按钮
    }
  },
  computed: {
    columns () {
      const _this = this
      // 差价归属
      const jcgsFormat = function (record, data, h) {
        const colors = { 'ASSIGN': '#00aaff', 'SUPERIORS': '#ff0000', 'HEAD': '#55aa7f' }
        if (data) {
          return (
            data.map(item => {
              return (
                <a-tag style="margin:5px;" color={colors[item.rebateParentType]}>{item.parentDealer.dealerName}({Number(item.allotRate * 100).toFixed(2) + '%'})</a-tag>
              )
            })
          )
        }
        return '--'
      }
      // 操作按钮
      const actionFormat = function (record, data, h) {
        if (_this.isTeyue) {
          return (<div>
            <a-button
              size="small"
              type="link"
              class="button-error"
              onClick={(e) => _this.handleDel(record, e)}
            >删除</a-button>
          </div>)
        }
        return (
          <div>
            <a-button
              size="small"
              type="link"
              class="button-info"
              onClick={(e) => _this.handleEdit(record, e)}
            >编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              onClick={(e) => _this.handleDel(record, e)}
            >删除</a-button>
          </div>
        )
      }
      // 表格展开收起功能
      const expendFormat = function (record, data, h) {
        if (_this.isTeyue) {
          return (<span>-</span>)
        }
        const hasExpend = _this.expandOption.expandedRowKeys.indexOf(record.id)
        if (hasExpend >= 0) {
          return (
            <span style="cursor:pointer;">收起</span>
          )
        }
        return (
          <span style="cursor:pointer;">展开</span>
        )
      }

      const arr = [
        { field: '', key: 'x', type: (this.isTeyue ? '-' : 'expand'), title: '品类', width: '5%', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return expendFormat(row, row[column.field], h) } },
        { title: '上级经销商', field: 'superDealerName', width: '20%', key: 'h', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '差价归属方', field: 'rebateDealerList', width: '65%', key: 'k', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return jcgsFormat(row, row[column.field], h) } },
        { title: '操作', field: 'action', width: '10%', key: 's', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return actionFormat(row, row[column.field], h) } }
      ]
      return arr
    }
  },
  methods: {
    // 给可控属性重新赋值
    changeExpandedRowKeys (keys) {
      this.expandOption.expandedRowKeys = keys
    },
    // 展开全部
    expandAll () {
      this.expandOption.expandedRowKeys = this.list.map((x) => x.id)
    },
    // 折叠全部
    foldAll () {
      this.expandOption.expandedRowKeys = []
    },
    // 筛选数据
    filterData (data, queryParam) {
      return data.filter(s => {
        let cs = true
        let bs = true
        const plen = Object.keys(queryParam).length
        const xi = queryParam.productBrandSn ? 3 : 2
        bs = queryParam.productBrandSn ? s.productBrandSn == queryParam.productBrandSn : true
        if (plen == xi) {
          cs = queryParam.productTypeSn1 == s.productTypeSn1
        } else if (plen == xi + 1) {
          cs = queryParam.productTypeSn1 == s.productTypeSn1 && queryParam.productTypeSn2 == s.productTypeSn2
        } else if (plen == xi + 2) {
          cs = queryParam.productTypeSn1 == s.productTypeSn1 && queryParam.productTypeSn2 == s.productTypeSn2 && queryParam.productTypeSn3 == s.productTypeSn3
        }
        console.log(queryParam, bs, cs, xi, plen)
        return queryParam.productBrandSn ? bs && cs : cs
      })
    },
    // 组装数据
    formatData (listData, queryParam) {
      // 格式化数据
      const ret = []
      const no = 0
      for (let i = 0; i < listData.length; i++) {
        const item = listData[i]
        // 筛选品牌 一级、二级、三级分类数据 渲染展开表格
        const rebateScopeList = item.rebateScopeList ? this.filterData(item.rebateScopeList, queryParam) : [{ productBrandName: null, productTypeName1: null, productTypeName2: null, productTypeName3: null }]
        // SUPERIORS 上级经销商    HEAD 总部经销商    ASSIGN 指定经销商
        const supDealerList = item.rebateDealerList.find(b => b.rebateParentType == 'SUPERIORS')
        const headDealerList = item.rebateDealerList.find(b => b.rebateParentType == 'HEAD')
        const zdDealerList = item.rebateDealerList.filter(b => b.rebateParentType == 'ASSIGN')
        // this.checkedDealerSn.push(rebateScopeList)
        // 差价归属组合
        const rebateDealerList = []
        if (supDealerList) {
          rebateDealerList.push(supDealerList)
        }
        zdDealerList && zdDealerList.map(zd => {
          rebateDealerList.push(zd)
        })
        if (headDealerList) {
          rebateDealerList.push(headDealerList)
        }
        for (let j = 0; j < rebateScopeList.length; j++) {
          rebateScopeList[j].no = j + 1
          rebateScopeList[j].dealerUpsSn = item.dealerUpsSn
          rebateScopeList[j].dealerSn = item.dealerSn
        }
        ret.push({
          no: i + 1,
          id: item.id,
          superDealerName: supDealerList.parentDealer.dealerName,
          dealerUpsSn: item.dealerUpsSn,
          dealerSn: item.dealerSn,
          rebateDealerList: rebateDealerList,
          childData: rebateScopeList
        })
      }

      return ret.filter(item => item.childData.length > 0)
    },
    // 列表数据查询
    searchTable (queryParam) {
      if (this.dataSource.length) {
        this.$emit('loaded', this.dataSource)
        this.list = this.formatData(this.dataSource, queryParam)
        this.showEmpty = this.list.length <= 0
      } else {
        this.dataSource = []
        this.list = []
        this.disabled = true
        this.spinning = true
        // 品类列表
        dealerUpsList(queryParam).then(res => {
          this.$emit('loaded', res.data || [])
          this.dataSource = res.data || []
          // 处理数据
          this.list = this.formatData(this.dataSource, queryParam)
          this.showEmpty = this.list.length <= 0
          this.tableHeight = (this.showEmpty ? 0 : this.maxHeight) + 'px'
          this.spinning = false
          this.disabled = false
        })
      }
    },
    // 编辑
    handleEdit (record, e) {
      console.log(e)
      e.stopPropagation()
      const row = this.dataSource.find(item => item.dealerUpsSn == record.dealerUpsSn && item.dealerSn == record.dealerSn)
      this.$emit('edit', row)
    },
    // 删除
    handleDel (record, e) {
      e.stopPropagation()
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后，将解除该品类差价设置归属关系。确定删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          dealerUpsDelete({ dealerUpsSn: record.dealerUpsSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              const rowIndex = _this.dataSource.findIndex(item => item.dealerUpsSn == record.dealerUpsSn && item.dealerSn == record.dealerSn)
              _this.dataSource.splice(rowIndex, 1)
              _this.$emit('del')
            }
            _this.spinning = false
          })
        }
      })
    },
    // 初始化
    pageInit (queryParam, isTeyue) {
      this.isTeyue = isTeyue
      // 获取列表
      this.searchTable(queryParam)
    }
  }
}
</script>
  <style lang="less">
  .empty-data{
        color: #999;
        text-align: center;
        padding: 20px;
    }
    .ve-table-body-td{
      .active-title{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px;
        background: #f3f8fa;
      }
    }
    .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-body-tr td.table-body-cell-no,
    .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-expand-tr td.table-body-cell-no{
      padding: 0;
    }
    .child-table-comp{
      padding: 10px;
    }
  </style>
