<template>
  <a-card :bordered="false">
    <!--<a-row :gutter="8">
      <a-col :span="5">
        <a-tree
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          @select="onSelect"
          :selectedKeys="selectedKeys"
          :treeData="storeTreeDate"
        />
      </a-col>
      <a-col :span="19">-->
    <div class="table-page-search-wrapper" @keyup.enter="handleEnter">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="所属公司">
              <a-select @change="handleCompanyChange" v-model="queryParam.useCompany" placeholder="请选择">
                <a-select-option
                  v-for="({deptId, name}) in companyList"
                  :key="deptId"
                  :label="name"
                  :value="deptId">{{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="所属项目">
              <a-select v-model="queryParam.useProject" placeholder="请选择">
                <a-select-option
                  v-for="({deptId, name}) in projectList"
                  :key="deptId"
                  :label="name"
                  :value="deptId">{{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="年">
              <a-select v-model="queryParam.year" placeholder="请选择">
                <a-select-option
                  v-for="item in years"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="月">
              <a-select v-model="queryParam.month" placeholder="请选择">
                <a-select-option
                  v-for="item in months"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6 || 24" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button style="margin-left: 8px" v-if="$auth('store-stores-export')" type="primary" icon="download" @click="doExport">导出</a-button>
      <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && $auth('store-stores-del')">
        <a-menu slot="overlay">
          <a-popconfirm title="是否要删除所选数据？" @confirm="batchDelete()">
            <a-menu-item key="1"><a-icon type="delete" /><a>删除</a></a-menu-item>
          </a-popconfirm>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <span slot="delFlag" slot-scope="text">
        <badge
          :status="DictCache.COLOR.DELFLAG[text]"
          :text="delFlagMap[text]" />
      </span>
    </s-table>
    <!--</a-col>
    </a-row>-->
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getStorePage, deleteStores, fetchStore, exportStore, fetchStoreTree } from '@/api/store/storemonthreport'
import { queryDept, getDeptsAllByParentId } from '@/api/upms/dept'
import { exportSpareStore } from '@/api/store/sparestore'

export default {
  name: 'StoreList',
  components: {
    STable,
    Ellipsis
  },
  props: {
    filter: {
      type: Number,
      default: -1
    }
  },
  data () {
    return {
      // 查询参数
      queryParam: {
        filter: this.filter
      },
      storeTreeDate: [],
      expandedKeys: [],
      years: [],
      months: [],
      autoExpandParent: true,
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return `${(this.$refs.table.localPagination.current - 1) * this.$refs.table.localPagination.pageSize + index + 1}`
          }
        },
        {
          title: '备件类型',
          dataIndex: 'spareTypeName'
        },
        {
          title: '期初余额',
          dataIndex: 'lastMonthAccount'
        },
        {
          title: '本期入库',
          dataIndex: 'inStoreAccount'
        },
        {
          title: '本期出库',
          dataIndex: 'outStoreAccount'
        },
        {
          title: '期末余额',
          dataIndex: 'currentMonthAccount'
        },
        {
          title: '库管员',
          dataIndex: 'createdUserName'
        }
      ],
      // 下拉框map
      typeMap: {},
      levelMap: {},
      companyList: {},
      projectList: {},
      delFlagMap: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        parameter = {
          ...parameter,
          ...this.queryParam,
          dataScope: {
          }
        }
        return getStorePage(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  created () {
    // 下拉框map
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.STORE_LEVEL)
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.STORE_TYPE)
    this.delFlagMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.DELFLAG)
    this.tableOption()
    this.init()
  },
  methods: {
    init () {
      var myDate = new Date()
      this.queryParam.year = myDate.getFullYear()// 获取当前年
      this.queryParam.month = myDate.getMonth()// 获取当前月
      this.initSelectYear(myDate.getFullYear())
      this.initSelectMonth()
    },
    initSelectYear (year) {
      this.years = []
      for (let i = 0; i < 3; i++) {
        this.years.push({ value: (year - i), label: (year - i) + '年' })
      }
    },
    initSelectMonth () {
      this.months = []
      for (let i = 1; i <= 12; i++) {
        this.months.push({ value: i, label: i + '月' })
      }
    },
    tableOption () {
      this.setTree()
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: false,
                name: record.id
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    setTree (record = {}) {
      queryDept({ nature: this.DictCache.VALUE.SYS_DEPT_NATURE.FEN_GONG_SI }).then(res => {
        this.companyList = res.data
      })
      getDeptsAllByParentId({ nature: this.DictCache.VALUE.SYS_DEPT_NATURE.XIANG_MU_BU }).then(res => {
        this.projectList = res.data
      })
    },
    handleCompanyChange (value) {
      this.projectList = null
      getDeptsAllByParentId({ deptId: value, nature: this.DictCache.VALUE.SYS_DEPT_NATURE.XIANG_MU_BU }).then(res => {
        this.projectList = res.data
      })
    },
    batchDelete (id) {
      let ids = []
      if (this.BaseTool.String.isBlank(id)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要删除的记录')
          return
        }
        ids = this.selectedRows.map(item => item.id)
      } else {
        ids = [id]
      }
      deleteStores(ids).then(res => {
        this.$message.info('删除成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
        filter: this.filter
      }
      this.$refs.table.refresh(true)
    },
    doExport () {
      const parameter = {
        ...this.queryParam
      }
      exportStore(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    handleCopy (record) {
      fetchStore({ id: record.id }).then(res => {
        const modal = this.$refs.baseModal
        res.data.id = null
        modal.base(res.data)
      })
    },
    handleEnter () {
      this.$refs.table.refresh(true)
    },
    onSelect: function (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.queryParam.parentId = selectedKeys.length > 0 ? selectedKeys[0] : ''
      this.$refs.table.refresh(true)
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    }
  }
}
</script>
