<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 v-decorator="['cdepcode', {rules: [{required: true, message: '申请部门不能为空'}]}]" placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in deptMap"
                  :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 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"
                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                v-decorator="['projectId']"
                placeholder="请选择"
              >
              </a-tree-select>
            </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"
      >
        <template slot="num" slot-scope="text, record">
          <a-input v-model="record.num" />
        </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 } 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: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '物料名称',
          dataIndex: 'spareName'
        },
        {
          title: '存货编码',
          dataIndex: 'no'
        },
        {
          title: '规格型号',
          dataIndex: 'ggxh'
        },
        {
          title: '仓库名称',
          dataIndex: 'storeName'
        },
        {
          title: '货架号',
          dataIndex: 'storePosition'
        },
        {
          title: '申请数量',
          dataIndex: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      typeMap: {},
      ipqcMap: [],
      flagMap: {},
      model: {},
      sbId: null,
      rows: [],
      sortNums: [],
      params: {},
      directorMap: [],
      infoNum: 0,
      cptcodeMap: {},
      deptMap: {},
      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.cbustypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.LONG_YAN_PURCHASE_BUSINESS_TYPE)
    this.soMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SO_TYPE)
  },
  methods: {
    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
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'sbId',
          'type',
          'oldOrNew',
          'projectId',
          'positionNo',
          'cptcode',
          'remark',
          'cdepcode',
          'cbustype',
          'planGetDate',
          'needDate'
        ])))
      })
    },
    // 获取巡检人与巡检主管信息

    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
        }
        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
        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 { 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) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = rows[i]
          selectData.storeNum = selectData.num
          selectData.num = 1
          data.push(selectData)
        }
      }
    },
    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>
