<template>
  <a-modal
    :title="title"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-card >
      <a-form :form="form">
        <row-list :col="1" v-show="false">
          <row-item>
            <a-form-item>
              <a-input v-decorator="['id']" type="hidden"/>
              <a-input v-decorator="['sbId']" type="hidden"/>
            </a-form-item>
          </row-item>
        </row-list>
        <row-list :col="2">
          <row-item >
            <a-form-item
              label="计划类型"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-select v-decorator="['type', { rules: [{required: true, message: '采购计划类型不能为空'}]}]" placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in typeMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </row-item>

          <row-item >
            <a-form-item
              label="请购原因"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-input
                v-decorator="['remark']"/>
            </a-form-item>
          </row-item>
          <row-item >
            <a-form-item
              label="采购类型"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-select v-decorator="['cptcode', { rules: [{required: true, message: '采购类型不能为空'}]}]" placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in cptcodeMap"
                  :key="value"
                  :label="label"
                  :value="value">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </row-item>
          <row-item >
            <a-form-item
              label="业务类型"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-select v-decorator="['cbustype', {rules: [{required: true, message: '业务类型不能为空'}]}]" placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in cbustypeMap"
                  :key="value"
                  :label="label"
                  :value="value">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </row-item>
          <row-item >
            <a-form-item
              label="采购厂区"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-select :disabled="title==='编辑'" v-decorator="['oldOrNew', {rules: [{required: true, message: '采购厂区不能为空'}]}]" @change="setTree">
                <a-select-option
                  v-for="(label,value) in flagMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </row-item>
          <row-item >
            <a-form-item
              label="申请部门"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-select :disabled="!oldOrNew" v-decorator="['cdepcode', {rules: [{required: true, message: '申请部门不能为空'}]}]" placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in oldOrNew===2?deptMap:deptNewMap"
                  :key="value"
                  :label="label"
                  :value="value">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </row-item>
          <!--          <row-item >-->
          <!--            <a-form-item-->
          <!--              label="需求跟踪方式"-->
          <!--              :labelCol="BaseTool.Constant.labelCol"-->
          <!--              :wrapperCol="BaseTool.Constant.wrapperCol"-->
          <!--            >-->
          <!--              <a-select v-decorator="['cestIrequireTrackStyle', {rules: [{required: true, message: '需求跟踪方式不能为空'}]}]" placeholder="请选择">-->
          <!--                <a-select-option-->
          <!--                  v-for="(label,value) in soMap"-->
          <!--                  :key="value"-->
          <!--                  :label="label"-->
          <!--                  :value="parseInt(value)">{{ label }}-->
          <!--                </a-select-option>-->
          <!--              </a-select>-->
          <!--            </a-form-item>-->
          <!--          </row-item>-->
          <row-item >
            <a-form-item
              label="计划到货日期"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-date-picker
                style="width: 100%"
                :disabled-date="disabledDate"
                @change="dateChange"
                :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
                v-decorator="['planGetDate', {rules: [{required: true, message: '计划到货日期不能为空'}]}]" />
            </a-form-item>
          </row-item>
          <row-item >
            <a-form-item
              label="需求日期"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-date-picker
                :disabled="!date"
                style="width: 100%"
                :disabled-date="disabledDate2"
                :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
                v-decorator="['needDate', {rules: [{required: true, message: '需求日期不能为空'}]}]" />
            </a-form-item>
          </row-item>
          <row-item >
            <a-form-item
              label="设备位号"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-input
                style="width: 70%"
                disabled
                v-decorator="['positionNo']" />
              <a-button :disabled="title==='编辑'" style="width: 30%" type="primary" @click="handleSbSelect">选择</a-button>
            </a-form-item>
          </row-item>
          <!-- <row-item >
            <a-form-item
              label="关联项目"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-tree-select
                style="width: 100%"
                :treeData="treeData"
                :showSearch="true"
                tree-node-filter-prop="title"
                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                v-decorator="['projectId']"
                placeholder="请选择"
              >
              </a-tree-select>
            </a-form-item>
          </row-item> -->
          <!-- <row-item >
            <a-form-item
              label="物资描述"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-textarea
                v-decorator="['cdefine11', { rules: [{required: true, message: '物资描述不能为空'}]}]"/>
            </a-form-item>
          </row-item> -->
          <!-- <row-item >
            <a-form-item
              label="物料简述"
              :labelCol="BaseTool.Constant.labelCol"
              :wrapperCol="BaseTool.Constant.wrapperCol"
            >
              <a-textarea
                v-decorator="['cdefine12', { rules: [{required: true, message: '物料简述不能为空'}]}]"/>
            </a-form-item>
          </row-item> -->
        </row-list>
      </a-form>
    </a-card>
    <a-card>
      <div class="table-operator" style="margin-bottom: 8px;">
        <a-button size="small" :disabled="!oldOrNew" type="primary" @click="handleSpareStoreSelect">
          <a-icon type="plus"/>
          物料库添加
        </a-button>
        <!-- <a-button size="small" :disabled="!(oldOrNew&&sbId)" style="margin-left:20px;" type="primary" @click="handleBomSpareStoreSelect">
          <a-icon type="plus"/>
          BOM添加
        </a-button> -->
      </div>
      <a-table
        bordered
        :data-source="data"
        :columns="columns"
        tableLayout="auto"
        rowKey="id"
        :scroll="{ x: 1500 }"
      >
        <template slot="iexchrate" slot-scope="text, record">
          <a-input-number v-model="record.iexchrate" :step="0.01" />
        </template>
        <template slot="funitprice" slot-scope="text, record" >
          <a-input-number v-model="record.funitprice" :step="0.0001" @blur="computeTax(record,1)" />
        </template>
        <template slot="fmoney" slot-scope="text, record">
          <a-input-number v-model="record.fmoney" :step="0.01" @blur="computeTax(record,2)" />
        </template>
        <template slot="num" slot-scope="text, record">
          <a-input-number v-model="record.num" :min="1" @blur="computeTax(record,1)" />
        </template>
        <template slot="ipertaxrate" slot-scope="text, record">
          <a-input-number
            v-model="record.ipertaxrate"
            :step="0.01"
            :formatter="value => `${value}%`"
            :parser="value => value.replace('%', '')" />
        </template>
        <template slot="cbmemo" slot-scope="text, record">
          <a-input v-model="record.cbmemo" />
        </template>
        <template slot="cdefine28" slot-scope="text, record">
          <a-input v-model="record.cdefine28" />
        </template>
        <template slot="cdefine22" slot-scope="text, record">
          <a-input v-model="record.cdefine22" />
        </template>
        <span slot="action" slot-scope="record">
          <template>
            <a-popconfirm title="是否要删除该条数据？" @confirm="handleDelOne(record)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </span>
      </a-table>
    </a-card>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <sb-info-select-modal ref="sbInfoSelectModal" @selected="handleSbSelectd"/>
    <spare-store-select-modal ref="spareStoreSelectModal" @selected="handleSpareStoreSelected"/>
    <BomSpareStoreSelectModal ref="bomSpareStoreSelectModal" @selected="handleSpareStoreSelected"/>

  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import moment from 'moment'
import { addPurchaseOrder2, updatePurchaseOrder2, getPurchasePrice } from '@/api/purchase/purchase-order'
import SbInfoSelectModal from './SbInfoSelectModal'
import SpareStoreSelectModal from '@/views/store/sparestore/modules/SpareStoreSelectModalYY3.vue'
import BomSpareStoreSelectModal from './SpareStoreSelectModalYY.vue'
import { fetchProjectTree } from '@/api/project/project'

export default {
  name: 'BaseFillGather',
  components: {
    SpareStoreSelectModal,
    SbInfoSelectModal,
    BomSpareStoreSelectModal

  },
  data () {
    return {
      form: this.$form.createForm(this),
      visible: false,
      title: '新增',
      data: [],
      treeData: [],
      columns: [
        {
          title: '序号',
          width: 50,
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '物料名称',
          width: 100,
          dataIndex: 'spareName'
        },
        {
          title: '存货编码',
          width: 100,
          dataIndex: 'no'
        },
        {
          title: '规格型号',
          width: 100,
          dataIndex: 'ggxh'
        },
        {
          title: '仓库名称',
          width: 100,
          dataIndex: 'storeName'
        },
        {
          title: '货架号',
          width: 150,
          dataIndex: 'storePosition'
        },
        {
          title: '批号',
          width: 100,
          dataIndex: 'cbatch'
        },
        {
          title: '需求人',
          dataIndex: 'cdefine22',
          width: 150,
          scopedSlots: { customRender: 'cdefine22' }
        },
        {
          title: '使用地点',
          dataIndex: 'cdefine28',
          width: 150,
          scopedSlots: { customRender: 'cdefine28' }
        },
        {
          title: '物资描述',
          dataIndex: 'cbmemo',
          width: 150,
          scopedSlots: { customRender: 'cbmemo' }
        },
        {
          title: '汇率',
          dataIndex: 'iexchrate',
          width: 150,
          scopedSlots: { customRender: 'iexchrate' }
        },
        {
          title: '本币无税单价',
          dataIndex: 'funitprice',
          width: 150,
          scopedSlots: { customRender: 'funitprice' }
        },
        {
          title: '税率',
          dataIndex: 'ipertaxrate',
          width: 150,
          scopedSlots: { customRender: 'ipertaxrate' }
        },
        {
          title: '申请数量',
          dataIndex: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },

        {
          title: '本币价税合计',
          dataIndex: 'fmoney',
          width: 150,
          scopedSlots: { customRender: 'fmoney' }

        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      typeMap: {},
      ipqcMap: [],
      flagMap: {},
      model: {},
      sbId: null,
      rows: [],
      sortNums: [],
      params: {},
      directorMap: [],
      infoNum: 0,
      cptcodeMap: {},
      deptMap: {},
      deptNewMap: {},
      soMap: {},
      date: false,
      cbustypeMap: {},
      confirmLoading: false,
      oldOrNew: null
    }
  },

  created () {
    this.flagMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PROJECT_NEW_AND_OLD)
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.LONG_YAN_PURCHASE_TYPE)
    this.cptcodeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.LONG_YAN_PURCHASE_ORDER_PLAN_TYPE)
    this.deptMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YONG_YOU_DEPT)
    this.deptNewMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YONG_YOU_DEPT_NEW)
    this.cbustypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.LONG_YAN_PURCHASE_BUSINESS_TYPE)
    this.soMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SO_TYPE)
  },
  methods: {
    computeTax (record, type) {
      if (type === 1) {
        console.log(record)
        const data = (record.funitprice * record.num * (1 + record.ipertaxrate / 100)).toFixed(2)
        record.fmoney = isNaN(data) ? 0 : data
      } else {
        const data = (record.fmoney / (record.num * (1 + record.ipertaxrate / 100))).toFixed(4)
        record.funitprice = isNaN(data) ? 0 : data
      }
      this.$forceUpdate()
    },
    disabledDate (current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day')
    },
    disabledDate2 (current) {
      // Can not select days before today and today
      return current && current <= this.date
    },
    dateChange (data) {
      console.log(data)
      this.date = data
    },
    base (record) {
      this.visible = true
      if (this.BaseTool.Object.isBlank(record)) {
        this.title = '新增'
        return
      }
      this.title = '编辑'
      this.data = record.detailVOS
      this.setTree(record.oldOrNew)
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'sbId',
          'type',
          'oldOrNew',
          'projectId',
          'positionNo',
          'cdefine11',
          'cdefine12',
          'cptcode',
          'remark',
          'cdepcode',
          'cbustype',
          'planGetDate',
          'needDate',
          'cdefine22',
          'cdefine28'
        ])))
      })
    },
    // 获取巡检人与巡检主管信息

    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base({})
    },
    handleSbSelectd (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.sbId = key
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbId': key,
          'positionNo': row.positionNo
        }))
      })
    },
    setTree (val) {
      console.log(val)
      this.oldOrNew = val
      fetchProjectTree({
        flag: val
      }).then((res) => {
        this.treeData = res.data
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      // this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          Object.values(errors).map(item => {
            this.$message.error(item.errors[0].message)
          })
          this.confirmLoading = false
          return
        }
        let status = 0
        values.needDate = values.needDate ? this.BaseTool.Date.formatter(values.needDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        values.planGetDate = values.planGetDate ? this.BaseTool.Date.formatter(values.planGetDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN) : null
        values.detailDTOS = this.data.map(item => {
          if (!item.funitprice) {
            status++
            this.$message.error('请填写' + item.spareName + '单价')
          }
          item.funitprice = (+item.funitprice).toFixed(4)
          item.ipertaxrate = (+item.ipertaxrate).toFixed(2)
          item.fmoney = (+item.fmoney).toFixed(2)
          return item
        })
        if (status !== 0) {
          return
        }
        if (values.id) {
          updatePurchaseOrder2(values).then(res => {
            this.$message.success('修改成功！')
            this.handleCancel()
          })
        } else {
          addPurchaseOrder2(values).then(res => {
            this.$message.success('创建成功！')
            this.handleCancel()
          })
        }
      })
    },
    handleSpareStoreSelect () {
      console.log(this.oldOrNew)
      this.$refs.spareStoreSelectModal.base({ tokenType: this.oldOrNew })
    },
    handleBomSpareStoreSelect () {
      this.$refs.bomSpareStoreSelectModal.base({ tokenType: this.oldOrNew, sbId: this.sbId })
    },
    handleSpareStoreSelected (record, keys, rows) {
      console.log(rows)
      const codes = []
      const { data } = this
      for (let i = 0; i < rows.length; i++) {
        let find = false
        for (let j = 0; j < data.length; j++) {
          if (rows[i].spareId === data[j].spareId && rows[i].cbatch === data[j].cbatch) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = this.BaseTool.Object.copy(rows[i])
          codes.push(selectData.no)
          selectData.storeNum = selectData.num
          selectData.num = 1
          selectData.iexchrate = 1
          selectData.ipertaxrate = 13
          data.push(selectData)
        }
      }
      getPurchasePrice({
        codes: codes.join(),
        isNew: this.oldOrNew
      }).then(res => {
        data.forEach(item => {
          item.funitprice = res.data.find(price => item.no === price.cinvCode).iunitPrice
          const data = (item.funitprice * item.num * (1 + item.ipertaxrate / 100)).toFixed(2)
          item.fmoney = isNaN(data) ? 0 : data
        })
        this.$forceUpdate()
      })
    },
    handleDelOne (record) {
      const data = [...this.data]
      this.data = data.filter(item => record.spareId !== item.spareId)
    },
    handleCancel (values) {
      this.visible = false
      this.data = []
      this.date = null
      this.params = {}
      this.form.resetFields()
      this.sbId = null
      this.oldOrNew = null
      this.$emit('ok', values)
    }

  }
}
</script>
<style lang="less" scoped>
.tooltip{
  font-size:20px;
  color:#ccc;
  &:hover {
  color:#2f54eb;
  }
}
</style>
