<template>
  <a-modal
    :title="modalTitle"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-steps class="steps" :current="currentTab">
      <a-step title="选择采购明细" />
      <a-step title="修改主条款明细" />
      <a-step title="确认" />
    </a-steps>
    <title-divider title="主条款信息" v-show="currentTab=== 2" width="90px"></title-divider>
    <a-table
      v-show="currentTab === 1 || currentTab=== 2"
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
    >
      <template slot="name" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',name'" @change="$event => onStringChange($event, record.id, 'name')" />
        </div>
      </template>
      <template slot="model" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',model'" @change="$event => onStringChange($event, record.id, 'model')" />
        </div>
      </template>
      <template slot="unit" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',unit'" @change="$event => onStringChange($event, record.id, 'unit')" />
        </div>
      </template>
      <template slot="remark" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',remark'" @change="$event => onStringChange($event, record.id, 'remark')" />
        </div>
      </template>
      <template slot="quantity" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',quantity'" @change="$event => onQuantityChange($event, record.id, 'quantity')" />
        </div>
      </template>
      <template slot="price" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',price'" @change="$event => onPriceChange($event, record.id, 'price')" />
        </div>
      </template>
      <template slot="totalMoney" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.id + ',totalMoney'" @change="$event => onStringChange($event, record.id, 'totalMoney')" />
        </div>
      </template>
      <!--      <span slot="action" slot-scope="record">-->
      <!--        <template>-->
      <!--          <operation-button-->
      <!--            :show-divider="false"-->
      <!--            v-if="$auth('purchase-purchase-contract-main-lists-del')"-->
      <!--            :type="2"-->
      <!--            title="是否要删除该条数据？"-->
      <!--            @confirm="batchDelete(record)">删除</operation-button>-->
      <!--        </template>-->
      <!--      </span>-->
    </a-table>
    <title-divider v-show="currentTab=== 2" title="明细清单" width="90px"></title-divider>
    <purchase-contract-list ref="contractList" v-show="currentTab=== 0 || currentTab=== 2"></purchase-contract-list>
    <template slot="footer">
      <a-button v-show="currentTab!== 0" style="margin-left: 8px" @click="prev()">上一步</a-button>
      <a-button style="margin-left: 8px" v-show="currentTab!== 2" type="primary" @click="next()">下一步</a-button>
      <a-button :loading="confirmLoading" style="margin-left: 8px" v-show="currentTab=== 2" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import PurchaseContractList from '../PurchaseContractList'
import { getPurchaseContractListPage } from '@/api/purchase/purchase-contract-list'

export default {
  name: 'BasePurchaseOrderContractMainList',
  components: { PurchaseContractList },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      unitMap: {},
      typeMap: {},
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          checked: true,
          width: 70,
          customRender: (text, record, index) => {
            return `${index + 1}`
          }
        },
        {
          title: '申购明细',
          dataIndex: 'name',
          checked: true,
          width: 120,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '型号',
          dataIndex: 'model',
          checked: true,
          width: 120,
          scopedSlots: { customRender: 'model' }
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          checked: true,
          width: 100,
          scopedSlots: { customRender: 'quantity' }
          // customRender: (text, record, index) => {
          //   return this.BaseTool.Amount.formatter(text)
          // }
        },
        {
          title: '单位',
          dataIndex: 'unit',
          checked: true,
          width: 100,
          scopedSlots: { customRender: 'unit' }
        },
        {
          title: '单价',
          dataIndex: 'price',
          checked: true,
          width: 100,
          scopedSlots: { customRender: 'price' }
          // customRender: (text, record, index) => {
          //   return this.BaseTool.Amount.formatter(text)
          // }
        },
        {
          title: '总价',
          dataIndex: 'totalMoney',
          checked: true,
          width: 100,
          scopedSlots: { customRender: 'totalMoney' }
          // customRender: (text, record, index) => {
          //   return this.BaseTool.Amount.formatter(text)
          // }
        },
        // {
        //   title: '整机编号',
        //   dataIndex: 'machineNo',
        //   checked: true,
        //   width: 180
        // },
        // {
        //   title: '发动机型号',
        //   dataIndex: 'engineModel',
        //   checked: true,
        //   width: 180
        // },
        // {
        //   title: '发动机编号',
        //   dataIndex: 'engineNo',
        //   checked: true,
        //   width: 180
        // },
        {
          title: '备注',
          dataIndex: 'remark',
          checked: true,
          width: 150,
          scopedSlots: { customRender: 'remark' }
        }
        // {
        //   title: '操作',
        //   key: 'action',
        //   width: '200px',
        //   checked: true,
        //   fixed: 'right',
        //   align: 'center',
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      dataSource: [],
      currentTab: 0,
      contractMainListId: '-1'
    }
  },
  props: {},
  created () {
    // 下拉框map
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PROJECT_UNIT)
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_TYPE)
  },
  methods: {
    base (record, contractId) {
      this.visible = true
      this.currentTab = 0
      this.BaseTool.ListForm.clearOneList(this)
      this.BaseTool.ListForm.clearTwoList(this)
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.addFlag = true
        this.modalTitle = '添加合同主清单'
        const id = this.BaseTool.String.uuid()
        this.contractMainListId = id
        this.$nextTick(() => {
          this.BaseTool.ListForm.initTwoList(this, id)
          const modal = this.$refs.contractList
          modal.base(id, true)
        })
      }
      // this.addFlag = false
      // this.modalTitle = '编辑合同主清单'
      // this.contractMainListId = record.id
      // // 日期处理
      // this.$nextTick(() => {
      //   setFieldsValue(Object.assign(pick(record, [
      //     'id',
      //     'demandPlanId',
      //     'purchasePlanId',
      //     'purchaseApplyId',
      //     'purchaseOrderId',
      //     'contractId',
      //     'tempFlag',
      //     'name',
      //     'model',
      //     'machineNo',
      //     'engineModel',
      //     'engineNo',
      //     'quantity',
      //     'unit',
      //     'price',
      //     'totalMoney',
      //     'remark',
      //     'delFlag'
      //   ])))
      //   this.BaseTool.ListForm.initTwoList(this, record.id)
      //   const modal = this.$refs.contractList
      //   modal.base(record.id, false)
      // })
    },
    onStringChange (e, id, attr) {
      const value = e.target.value
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.id === id)
      if (target) {
        target[attr] = value
        this.dataSource = dataSource
      }
    },
    onQuantityChange (e, id, attr) {
      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[attr] = value
        const price = target['price']
        if (price) {
          target['totalMoney'] = Math.floor(value * target['price'] * 10000) / 10000
        }
        this.dataSource = dataSource
      }
    },
    onPriceChange (e, id, attr) {
      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[attr] = value
        const quantity = target['quantity']
        if (quantity) {
          target['totalMoney'] = Math.floor(value * target['quantity'] * 10000) / 10000
        }
        this.dataSource = dataSource
      }
    },
    save () {
      // 一条 清单放第一个
      if (this.dataSource.length === 1) {
        const first = this.dataSource[0]
        first.id = this.contractMainListId
        this.BaseTool.ListForm.setTwoListValues(this, first, first.id)
        this.BaseTool.ListForm.pushOneListAdd(this, first)
      }
      // 超过1条 清单放第一个
      if (this.dataSource.length > 1) {
        const first = this.dataSource[0]
        first.id = this.contractMainListId
        this.BaseTool.ListForm.setTwoListValues(this, first, first.id)
        this.BaseTool.ListForm.pushOneListAdd(this, first)
        for (let i = 1; i < this.dataSource.length; i++) {
          this.BaseTool.ListForm.pushOneListAdd(this, this.dataSource[i])
        }
      }
      this.confirmLoading = false
      this.handleCancel({})
    },
    loadData () {
      const parameter = {
        pageSize: 9999,
        contractMainListId: this.contractMainListId,
        minStatus: this.DictCache.VALUE.PURCHASE_LIST_STATUS.PURCHASE_LIST_STATUS_CONTRACT,
        dataScope: {
          sortBy: 'desc',
          sortName: 'update_time'
        }
      }
      return getPurchaseContractListPage(parameter)
        .then(res => {
          const data = res.data
          data.rows = this.BaseTool.ListForm.getTwoListHandledRows(this, data.rows, this.contractMainListId)
          const dataSource = []
          if (data.rows.length <= 5) {
            data.rows.forEach(item => {
              dataSource.push({
                id: item.id,
                name: item.name,
                model: item.specs,
                quantity: item.quantity,
                unit: item.unit,
                goodsId: item.goodsId,
                price: item.supplyPrice,
                totalMoney: item.supplyTotalMoney,
                remark: item.remark
              })
            })
          } else {
            let totalMoney = 0
            data.rows.forEach(item => {
              totalMoney += item.supplyTotalMoney
            })
            dataSource.push({
              id: this.contractMainListId,
              name: this.typeMap[this.$store.getters.purchaseType],
              model: '-',
              quantity: '1',
              unit: '批',
              price: totalMoney,
              totalMoney: totalMoney,
              remark: '物资配件详见清单'
            })
          }
          this.dataSource = dataSource
        })
    },
    next () {
      if (this.currentTab === 0) {
        this.loadData()
      }
      this.currentTab += 1
    },
    prev () {
      this.currentTab -= 1
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
