<template>
  <a-card :bordered="false" v-if="visible">
    <div class="table-operator" v-if="!viewFlag">
      <a-button v-if="$auth('purchase-purchase-demand-plan-lists-edit')" type="primary" icon="plus" @click="handleSelect">选择</a-button>
      <a-button style="margin-left: 8px" v-if="$auth('purchase-purchase-demand-plan-lists-edit')" type="primary" icon="upload" @click="doImport">导入明细</a-button>
    </div>
    <a-table
      ref="table"
      size="small"
      rowKey="id"
      :columns="columnItems"
      :scroll="{x: 1, y: BaseTool.Constant.scrollY }"
      :data-source="dataSource"
      :alert="options.alert"
      :loading="loading"
      :showSizeChanger="showSizeChanger"
      :showPagination="showSizeChanger"
      :rowSelection="options.rowSelection"
    >
      <template slot="addQuantity" slot-scope="text, record">
        <div v-if="!viewFlag" class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',addQuantity'" @change="onAddQuantityChange($event)" />
        </div>
        <span v-if="viewFlag">{{ text }}</span>
      </template>
      <template slot="controlMoney" slot-scope="text, record">
        <div v-if="!viewFlag" class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',controlMoney'" @change="onValueChange($event)" />
        </div>
        <span v-if="viewFlag">{{ text }}</span>
      </template>
      <!--      <span slot="action" slot-scope="record">-->
      <!--        <template>-->
      <!--          <operation-button-->
      <!--            :showDivider="false"-->
      <!--            v-if="$auth('purchase-purchase-demand-plan-lists-edit')"-->
      <!--            @click="handleEdit(record)"-->
      <!--          >修改</operation-button>-->
      <!--        </template>-->
      <!--      </span>-->
    </a-table>
    <base-add-form ref="baseListModal" @ok="handleOk"/>
    <import-form-add ref="importModal" @ok="handleOk"></import-form-add>
    <purchase-demand-plan-list-select-modal ref="selectModal" :type="'checkbox'" @selected="handleSelected"></purchase-demand-plan-list-select-modal>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseAddForm from './list-modules/BaseAddForm'
import { getPurchaseDemandPlanListAddPage } from '@/api/purchase/purchase-demand-plan-list-add'
import PurchaseDemandPlanListSelectModal from '@/views/purchase/purchase-demand-plan/list-modules/PurchaseDemandPlanListSelectModal'
import ImportFormAdd from './list-modules/ImportFormAdd'

export default {
  name: 'PurchaseDemandPlanListListAdd',
  components: {
    STable,
    Ellipsis,
    PurchaseDemandPlanListSelectModal,
    ImportFormAdd,
    BaseAddForm
  },
  data () {
    return {
      // 查询参数
      queryParam: {
        pageSize: 9999
      },
      visible: false,
      demandPlanId: '-1',
      demandPlanAddId: '-1',
      showSizeChanger: false,
      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: '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 + record.addQuantity)
          }
        },
        {
          title: '增补数量',
          dataIndex: 'addQuantity',
          checked: true,
          width: 150,
          scopedSlots: { customRender: 'addQuantity' }
        },
        {
          title: '总价',
          dataIndex: 'totalMoney',
          checked: true,
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '控制金额',
          dataIndex: 'controlMoney',
          checked: true,
          width: 150,
          scopedSlots: { customRender: 'controlMoney' }
        },
        {
          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: {},
      dataSource: [],
      // 加载数据方法 必须为 Promise 对象
      // loadData: parameter => {
      //   parameter = {
      //     ...parameter,
      //     ...this.queryParam,
      //     demandPlanId: this.demandPlanId,
      //     demandPlanAddId: this.demandPlanAddId,
      //     dataScope: {
      //       sortBy: 'desc',
      //       sortName: 'update_time'
      //     }
      //   }
      //   if (!this.demandPlanId) {
      //     return getPurchaseDemandPlanListAddPage(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
      //         let planListControlMoney = 0
      //         let planListMoney = 0
      //         data.rows.forEach((item) => {
      //           planListControlMoney += item.controlMoney
      //           planListMoney += item.totalMoney
      //         })
      //         this.$emit('ok', planListControlMoney, planListMoney)
      //         return data
      //       })
      //   }
      //   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
      //       let planListControlMoney = 0
      //       let planListMoney = 0
      //       data.rows.forEach((item) => {
      //         planListControlMoney += item.controlMoney
      //         planListMoney += item.totalMoney
      //       })
      //       this.$emit('ok', planListControlMoney, planListMoney)
      //       return data
      //     })
      // },
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,

      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)
    this.tableOption()
  },
  methods: {
    base (demandPlanId, demandPlanAddId) {
      this.dataSource = []
      this.visible = true
      this.demandPlanId = demandPlanId
      this.demandPlanAddId = demandPlanAddId || '-1'
      if (this.isCreated) {
        this.handleOk()
      } else {
        this.initData()
        this.tableOption()
        this.isCreated = true
      }
    },
    doImport () {
      const type = this.$store.getters.purchaseType
      if (!type) {
        this.$message.error('请选择类型')
        return
      }
      this.$refs.importModal.base(type)
    },
    onAddQuantityChange (e) {
      const idStr = e.target.id
      const values = idStr.split(',')
      const id = values[0]
      const index = values[1]
      const value = parseFloat(e.target.value)
      if (value !== 0 && !value) {
        return
      }
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.id === id)
      if (target) {
        target[index] = value
        // target['quantity'] = target['quantity'] + value
        target['totalMoney'] = Math.floor((target['quantity'] + value) * target['price'] * 10000) / 10000
        this.dataSource = dataSource
        this.updateMainMoney()
      }
    },
    onValueChange (e) {
      const idStr = e.target.id
      const values = idStr.split(',')
      const id = values[0]
      const index = values[1]
      const value = e.target.value
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.id === id)
      if (target) {
        target[index] = value
        this.dataSource = dataSource
        this.updateMainMoney()
      }
    },
    updateMainMoney () {
      let planListControlMoney = 0
      let planListMoney = 0
      this.dataSource.forEach((item) => {
        planListControlMoney += item.controlMoney
        planListMoney += item.totalMoney
      })
      this.$emit('ok', planListControlMoney, planListMoney)
    },
    initData () {
      this.loading = true
      const parameter = {
        ...this.queryParam,
        demandPlanAddId: this.demandPlanAddId,
        dataScope: {
          sortBy: 'desc',
          sortName: 'update_time'
        }
      }
      return getPurchaseDemandPlanListAddPage(parameter)
        .then(res => {
          const data = res.data
          data.rows = this.BaseTool.ListForm.getOneListHandledRowsForEdit(this, data.rows, 'goodsId')
          this.$store.dispatch('setOneListAdd', data.rows)
          this.$store.dispatch('setCheckedRows', data.rows)
          this.dataSource = data.rows
          this.loading = false
          this.$emit('ok', {})
        })
    },
    handleSelect () {
      this.$refs.selectModal.base(null, { demandPlanId: this.demandPlanId, pageSize: 9999 })
    },
    handleSelected (record, keys, rows) {
      this.BaseTool.ListForm.pushOneListAddMoreForEdit(this, rows, 'goodsId')
      this.initData()
    },
    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
      }
    },
    handleEdit (record) {
      const modal = this.$refs.baseListModal
      modal.base(record)
    },
    handleView (record) {
      const modal = this.$refs.detailListModal
      modal.base(record)
    },
    handleOk () {
      this.initData()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleEnter () {
      this.initData()
    }
  }
}
</script>
