<template>
  <a-card :bordered="false" v-if="visible">
    <!--    <div class="table-page-search-wrapper" @keyup.enter="handleEnter" v-if="viewFlag">-->
    <!--      <a-form layout="inline">-->
    <!--        <a-row :gutter="48">-->
    <!--          <a-col :md="8" :sm="24">-->
    <!--            <a-form-item label="关键字">-->
    <!--              <a-input v-model="queryParam.keyword" placeholder="请输入名称/类型名称"/>-->
    <!--            </a-form-item>-->
    <!--          </a-col>-->
    <!--          <a-col :md="8 || 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 v-if="$auth('purchase-purchase-demand-plan-lists-add')" type="primary" icon="plus" @click="handleAdd">新增</a-button>-->
      <a-button style="margin-left: 8px" v-if="!viewFlag && $auth('purchase-purchase-demand-plans-edit')" type="primary" icon="upload" @click="doImport">导入明细</a-button>
      <a-button style="margin-left: 8px" v-if="$auth('purchase-purchase-demand-plan-lists-export')" type="primary" icon="download" @click="doExport">导出明细</a-button>
      <a-button style="margin-left: 8px" v-if="$auth('purchase-purchase-demand-plan-lists-export')" type="primary" icon="download" @click="downTemplate">下载模板</a-button>

      <a-dropdown v-action:edit v-if="!viewFlag && selectedRowKeys.length > 0 && $auth('purchase-purchase-demand-plan-lists-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="small"
      rowKey="id"
      :columns="columns"
      :scroll="{x: 1, y: BaseTool.Constant.scrollY }"
      :data="loadData"
      :alert="options.alert"
      :showSizeChanger="showSizeChanger"
      :showPagination="auto"
      :rowSelection="options.rowSelection"
    >
      <span slot="action" slot-scope="record">
        <template>
          <!--          <a @click="handleView(record)">查看</a>-->
          <operation-button
            :showDivider="false"
            v-if="$auth('purchase-purchase-demand-plan-lists-edit')"
            @click="handleEdit(record)"
          >修改</operation-button>
          <operation-button
            v-if="$auth('purchase-purchase-demand-plan-lists-del')"
            :type="2"
            title="此操作会直接删除数据，是否要删除该条数据？"
            @confirm="batchDelete(record.id)">删除</operation-button>
        </template>
      </span>
    </s-table>
    <base-form ref="baseListModal" @ok="handleOk"/>
    <detail ref="detailListModal"/>
    <import-form ref="importModal" @ok="handleOk"></import-form>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './list-modules/BaseForm'
import Detail from './list-modules/Detail'
import ImportForm from './list-modules/ImportForm'
import { getPurchaseDemandPlanListPage, exportPurchaseDemandPlanList, deletePurchaseDemandPlanLists } from '@/api/purchase/purchase-demand-plan-list'

export default {
  name: 'PurchaseDemandPlanListList',
  components: {
    STable,
    Ellipsis,
    BaseForm,
    ImportForm,
    Detail
  },
  data () {
    return {
      // 查询参数
      queryParam: {
        pageSize: 10
      },
      visible: false,
      demandPlanId: '-1',
      showSizeChanger: true,
      isCreated: false,
      columns: [],
      // 表头
      columnItems: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          checked: true,
          customRender: (text, record, index) => {
            return `${index + 1}`
          }
        },
        {
          title: '编号',
          dataIndex: 'no',
          checked: true,
          width: 200
        },
        // {
        //   title: '类别',
        //   dataIndex: 'type',
        //   checked: true,
        //   width: 90
        // },
        {
          title: '名称',
          dataIndex: 'name',
          checked: true,
          width: 120
        },
        {
          title: '规格',
          dataIndex: 'specs',
          checked: true,
          width: 90
        },
        {
          title: '单位',
          dataIndex: 'unit',
          checked: true,
          width: 90
        },
        {
          title: '单价',
          dataIndex: 'price',
          checked: true,
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          checked: true,
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '总价',
          dataIndex: 'totalMoney',
          checked: true,
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '超支数量',
          dataIndex: 'overQuantity',
          checked: true,
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '增补数量',
          dataIndex: 'addQuantity',
          checked: true,
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '控制金额',
          dataIndex: 'controlMoney',
          checked: true,
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '合同项目名称',
          dataIndex: 'contractName',
          checked: true,
          width: 120
        },
        {
          title: '合同项目数量',
          dataIndex: 'contractQuantity',
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '合同总金额',
          dataIndex: 'contractMoney',
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '合同项目单位',
          dataIndex: 'contractProjectUnit',
          width: 90
        },
        {
          title: '项目单位',
          dataIndex: 'projectUnit',
          width: 90,
          checked: true
        },
        {
          title: '已购数量',
          dataIndex: 'boughtQuantity',
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '已用金额',
          dataIndex: 'usedMoney',
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 100
        },
        {
          title: '创建人名称',
          dataIndex: 'createdUserName',
          width: 100
        },
        {
          title: '创建时间',
          dataIndex: 'createdTime',
          width: 100
        }
      ],
      // 下拉框map
      unitMap: {},
      planListControlMoney: 0,
      planListMoney: 0,
      contractProjectUnitMap: {},
      projectUnitMap: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        parameter = {
          ...parameter,
          ...this.queryParam,
          demandPlanId: this.demandPlanId,
          dataScope: {
            sortBy: 'desc',
            sortName: 'update_time'
          }
        }
        return getPurchaseDemandPlanListPage(Object.assign(parameter, this.queryParam))
          .then(res => {
            const data = res.data
            // data.rows = this.BaseTool.ListForm.getOneListHandledRows(this, data.rows)
            // data.total = res.data.rows.length
            // const planListControlMoney = 0
            // const planListMoney = 0
            // data.rows.forEach((item) => {
            // planListControlMoney += item.controlMoney
            //  planListMoney += item.totalMoney
            // })
            // console.log(planListControlMoney)
            this.$emit('ok', {})
            return data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  props: {
    viewFlag: {
      type: Boolean,
      default: false
    }
  },
  created () {
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_UNIT)
    this.contractProjectUnitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CONTRACT_PROJECT_UNIT)
    this.projectUnitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PROJECT_UNIT)
    if (!this.viewFlag) {
      this.columns = [
        ...this.columnItems,
        {
          title: '操作',
          key: 'action',
          width: '200px',
          fixed: 'right',
          checked: true,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
      this.optionAlertShow = true
    } else {
      this.columns = [
        ...this.columnItems
      ]
      this.optionAlertShow = false
    }
    this.tableOption()
  },
  methods: {
    base (demandPlanId) {
      this.visible = true
      this.addFlag = this.$store.getters.addFlag
      this.demandPlanId = demandPlanId
      if (this.isCreated) {
        this.handleOk()
      } else {
        this.tableOption()
        this.isCreated = true
      }
    },
    doImport () {
      const type = this.$store.getters.purchaseType
      if (!type) {
        this.$message.error('请选择类型')
        return
      }
      this.$refs.importModal.base(type, this.demandPlanId)
    },
    tableOption () {
      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
      }
    },
    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]
      }
      deletePurchaseDemandPlanLists(ids).then(res => {
        this.$message.info('删除成功')
        this.handleOk()
        this.$refs.table.clearSelected()
      })
    },
    handleEdit (record) {
      const modal = this.$refs.baseListModal
      modal.base(record)
    },
    handleView (record) {
      const modal = this.$refs.detailListModal
      modal.base(record)
    },
    handleAdd () {
      this.$refs.baseListModal.base(null)
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
        demandPlanId: this.demandPlanId
      }
      this.$refs.table.refresh(true)
    },
    doExport () {
      const parameter = {
        ...this.queryParam,
        demandPlanId: this.demandPlanId
      }
      exportPurchaseDemandPlanList(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    downTemplate () {
      let a = document.createElement('a')
      a.href = this.DictCache.getValueByCode(this.DictCache.TYPE.FILE_DOWNLOAD_TEMPLATE, 'PURCHASE_DOWNLOAD_TEMPLATE')
      a.target = "_blank"
      a.click()
    },
    handleEnter () {
      this.$refs.table.refresh(true)
    }
  }
}
</script>
