<template>
  <a-card size="small" :bordered="false" class="shoppingManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 操作按钮 -->
      <div ref="tableSearch" class="table-operator" style="border: 0;">
        <a-button id="shoppingManagementList-addType" v-if="$hasPermissions('B_addCategory')" type="primary" @click="addCategory('add')">新增类目</a-button>
      </div>
      <!-- 列表 -->
      <a-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+70+'px'}"
        size="small"
        :rowKey="(record) => record.categorySn"
        rowKeyName="categorySn"
        :columns="columns"
        :pagination="false"
        :dataSource="loadDataList"
        :scroll="{ y: tableHeight+70 }"
        @expand="expandChild"
        :expanded-row-keys.sync="expandedRowKeys"
        bordered>
        <!-- 图片 -->
        <template slot="imgs" slot-scope="text, record">
          <div class="addType-img" v-if="record.iconUrl">
            <img
              :src="record.iconUrl"
              alt="图片走丢啦"
              width="40"
              height="40"
              @click="handleImg(record)"
              :id="'shoppingManagementList-img-'+record.id"/>
          </div>
          <span v-else>--</span>
        </template>
        <!-- 状态 -->
        <template slot="enabledFlag" slot-scope="text, record">
          <a-switch
            :id="'shoppingManagementList-enableFlag-'+record.id"
            v-if="$hasPermissions('B_shoppingManagement_enabled')"
            checkedChildren="启用"
            unCheckedChildren="禁用"
            v-model="record.enableFlag"
            @change="e=>changeFlagHandle(e,record)"/>
          <span v-else :style="{color:(record.status==1?'#00aa00':'#999')}"> {{ record.status==1? '已启用': '已禁用' }} </span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-info"
            @click="handleEdit(record,'edit')"
            v-if="$hasPermissions('B_addCategory_edit')"
            :id="'shoppingManagementList-edit-btn'+record.id">编辑</a-button>
          <a-button
            size="small"
            type="link"
            class="button-info"
            @click="handleEdit(record,'addChild')"
            v-if="$hasPermissions('B_addChildCategory')&&(record.type && record.type=='root')&&(record.shopCategoryCount>=0&&record.shopProductCount==0)"
            :id="'shoppingManagementList-addChild-btn'+record.id">添加子类目</a-button>
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_addProduct')&&(record.shopProductCount>=0&&record.shopCategoryCount==0)||record.type!='root'"
            class="button-success"
            @click="handleAddProduct(record)"
            :id="'shoppingManagementList-addProduct-btn'+record.id">添加产品</a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            @click="handleDel(record)"
            v-if="$hasPermissions('B_delCategory')"
            :id="'shoppingManagementList-del-btn'+record.id">删除</a-button>
        </template>
      </a-table>
    </a-spin>
    <!-- 新增类目 -->
    <addCategoryModal
      v-drag
      ref="categoryModal"
      :pageType="pageType"
      :openModal="openCategoryModal"
      :parentData="parentData"
      @ok="handleCategoryOk"
      @close="closeCategory"></addCategoryModal>
    <!-- 查看图片 -->
    <imgShowModal v-drag ref="checkedImg" :openModal="openCheckedImgModal" @close="openCheckedImgModal=false"></imgShowModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { VSelect } from '@/components'
import addCategoryModal from './addCategoryModal.vue'
import imgShowModal from './imgShowModal.vue'
// 接口
import { shopCategoryList, getChildList, shopCategoryUpdateStatus, shopCategoryDel } from '@/api/shopCategory'
export default {
  name: 'ShoppingManagementList',
  mixins: [commonMixin],
  components: { VSelect, addCategoryModal, imgShowModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      openCategoryModal: false, // 打开新增类目弹窗
      // 表头
      columns: [
        { title: '类目名称', dataIndex: 'categoryName', width: '23%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '图片', scopedSlots: { customRender: 'imgs' }, width: '10%', align: 'center' },
        { title: '易码通优先级', dataIndex: 'sort', width: '10%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' }, ellipsis: true },
        { title: '创建时间', dataIndex: 'createDate', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        // { title: '状态', scopedSlots: { customRender: 'enabledFlag' }, width: '15%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '23%', align: 'center' }
      ],
      parentData: null, // 父级类目一行数据
      loadDataList: [], // 表格数据
      pageType: null, // 按钮类型
      expandedRowKeys: [], // 展开的类目sn合集
      openCheckedImgModal: false// 查看图片弹窗
    }
  },
  methods: {
    // 展开子级 获取子级数据
    expandChild (expanded, record) {
      if (expanded) {
        const _this = this
        _this.spinning = true
        getChildList({ categorySn: record.categorySn }).then(res => {
          if (res.status == 200) {
            const pos = this.loadDataList.findIndex(item => item.categorySn === record.categorySn)
            _this.loadDataList[pos].children = pos != -1 ? (res.data.shopCategoryList && res.data.shopCategoryList.length > 0) ? res.data.shopCategoryList : [] : []
            // 处理显示状态
            if (_this.loadDataList[pos].children && _this.loadDataList[pos].children.length > 0) {
              _this.loadDataList[pos].children.map(con => con.enableFlag = con.status == 1)
            }
          }
          _this.spinning = false
        })
      }
    },
    // 新增类目
    addCategory (typeVal) {
      this.pageType = typeVal
      this.openCategoryModal = true
    },
    // 新增类目成功
    handleCategoryOk () {
      this.getTabData()
    },
    // 关闭新增类目弹窗
    closeCategory () {
      this.pageType = null
      this.parentData = null
      this.openCategoryModal = false
    },
    // 编辑  添加子类目
    handleEdit (row, typeVal) {
      this.pageType = typeVal
      this.openCategoryModal = true
      this.parentData = row
      if (typeVal === 'edit') {
        this.$refs.categoryModal.getDetailData({ categorySn: row.categorySn })
      }
    },
    // 更新状态
    changeFlagHandle (e, row) {
      const _this = this
      _this.spinning = true
      const params = { categorySn: row.categorySn }
      params.status = row.status == 1 ? '0' : '1'
      shopCategoryUpdateStatus(params).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          row.enableFlag = e
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 添加产品
    handleAddProduct (row) {
      this.$router.push({ name: 'chooseProductList', params: { sn: row.categorySn } })
    },
    // 查看图片
    handleImg (row) {
      this.openCheckedImgModal = true
      const _this = this
      _this.$nextTick(() => {
        _this.$refs.checkedImg.pageInit(row.iconUrl)
      })
    },
    // 删除
    handleDel (row) {
      const _this = this
      if (row.shopCategoryCount > 0) {
        _this.$message.warning('请先删除子类目！')
        return
      }
      if (row.shopProductCount > 0) {
        _this.$message.warning('请先删除关联产品！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '删除后数据不可恢复，确认删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shopCategoryDel({ categorySn: row.categorySn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              if (row.type === 'root') {
                const pos = _this.loadDataList.findIndex(item => item.categorySn === row.categorySn)
                _this.loadDataList.splice(pos, 1)
              } else {
                const posNum = _this.loadDataList.findIndex(item => item.categorySn === row.parentSn)
                const indexNum = _this.loadDataList[posNum].children.findIndex(con => con.categorySn === row.categorySn)
                _this.loadDataList[posNum].children.splice(indexNum, 1)
                // 清空子级时，显示选择产品列表
                if (_this.loadDataList[posNum].children && _this.loadDataList[posNum].children.length === 0) {
                  _this.loadDataList[posNum].shopCategoryCount = 0

                  const i = _this.expandedRowKeys.findIndex(item => item === row.parentSn)
                  _this.expandedRowKeys.splice(i, 1)
                }
              }
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 获取表格数据
    getTabData () {
      this.spinning = true
      shopCategoryList({}).then(res => {
        let data
        if (res.status == 200) {
          data = res.data
          for (var i = 0; i < data.length; i++) {
            data[i].enableFlag = data[i].status == 1
            data[i].children = []
            data[i].type = 'root'
          }
        }
        this.loadDataList = res.data
        if (this.expandedRowKeys && this.expandedRowKeys.length > 0) {
          this.expandedRowKeys.forEach(item => {
            this.expandChild(true, { categorySn: item })
          })
        }
        this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      const _this = this
      _this.getTabData()
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 230
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .shoppingManagementList-wrap{
    height: 99%;
    .addType-img{
      img{
        object-fit: cover;
      }
    }
  }
</style>
