<template>
  <a-card :bordered="false" v-show="visible" class="card" :title="modalTitle">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right">
          <a-popconfirm title="提交审批操作过后将无法更改，确认进行该操作吗？" @confirm="save(DictCache.VALUE.PURCHASE_PLAN_STATUS.PURCHASE_PLAN_STATUS_SHE)">
            <a-button type="danger">提交审批</a-button>
          </a-popconfirm>
          <a-button style="margin-left: 8px" type="primary" @click="save()">保存</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>
    <title-divider title="基本信息" width="90px"></title-divider>
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['companyId']" type="hidden"/>
        <a-input v-decorator="['projectId']" type="hidden"/>
      </a-form-item>

      <row-list :col="2">
        <row-item>

          <a-form-item
            label="需求计划"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              @change="changePlan"
              v-decorator="['demandPlanId', {rules: [{required: true, message: '需求计划不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="item in demandPlans"
                :key="item.id"
                :label="item.name"
                :value="item.id">{{ item.name }}
              </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
              disabled="disabled"
              v-decorator="['companyName', {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
              disabled="disabled"
              v-decorator="['projectName', {rules: [{required: true, message: '项目名称不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="类型"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              disabled="disabled"
              v-decorator="['type', {rules: [{required: true, message: '类型不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                disabled="disabled"
                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
              type="number"
              style="width: 50%"
              addon-after="年"
              @change="generateName"
              v-decorator="['year', {rules: [{required: true, message: '年不能为空'}]}]">
            </a-input>
            <!--            <a-input-->
            <!--              type="number"-->
            <!--              style="width: 50%"-->
            <!--              @change="generateName"-->
            <!--              :min="1"-->
            <!--              v-decorator="['periodValue', {rules: [{required: true, message: '周期值不能为空'}]}]">-->
            <!--              <a-select-->
            <!--                style="width: 80px"-->
            <!--                slot="addonAfter"-->
            <!--                @change="generateName"-->
            <!--                v-decorator="['periodType', {initialValue: 1, rules: [{required: true, message: '周期类型不能为空'}]}]"-->
            <!--                placeholder="请选择">-->
            <!--                <a-select-option-->
            <!--                  v-for="(label,value) in periodTypeMap"-->
            <!--                  :key="value"-->
            <!--                  :label="label"-->
            <!--                  :value="parseInt(value)">{{ label }}-->
            <!--                </a-select-option>-->
            <!--              </a-select>-->

            <!--            </a-input>-->

          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['name', {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-->
        <!--              v-decorator="['billNo', {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-->
        <!--              style="width: 100%"-->
        <!--              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"-->
        <!--              v-decorator="['planDate', {rules: [{required: true, message: '日期不能为空'}]}]"/>-->
        <!--          </a-form-item>-->
        <!--        </row-item>-->
        <row-item>

          <a-form-item
            label="呈报"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['reportType', {rules: [{required: true, message: '呈报不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in reportTypeMap"
                :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%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['demandDate', {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-->
        <!--              v-decorator="['item']"/>-->
        <!--          </a-form-item>-->
        <!--        </row-item>-->

        <!--        <row-item>-->

        <!--          <a-form-item-->
        <!--            label="设备物资综述"-->
        <!--            :labelCol="BaseTool.Constant.labelCol"-->
        <!--            :wrapperCol="BaseTool.Constant.wrapperCol"-->
        <!--          >-->
        <!--            <a-textarea-->
        <!--              v-decorator="['summary']"/>-->
        <!--          </a-form-item>-->
        <!--        </row-item>-->
        <!--        <row-item>-->

        <!--          <a-form-item-->
        <!--            label="特殊情况"-->
        <!--            :labelCol="BaseTool.Constant.labelCol"-->
        <!--            :wrapperCol="BaseTool.Constant.wrapperCol"-->
        <!--          >-->
        <!--            <a-textarea-->
        <!--              v-decorator="['specialDescription']"/>-->
        <!--          </a-form-item>-->
        <!--        </row-item>-->
        <row-item>

          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-textarea
              v-decorator="['remark']"/>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <title-divider title="计划明细" width="90px"></title-divider>
    <purchase-plan-list ref="planList"/>
  </a-card></template>

<script>
import pick from 'lodash.pick'
import { addPurchasePlan, updatePurchasePlan } from '@/api/purchase/purchase-plan'
import { queryPurchaseDemandPlan } from '@/api/purchase/purchase-demand-plan'
import PurchasePlanList from '../PurchasePlanList'

export default {
  name: 'BasePurchasePlan',
  components: { PurchasePlanList },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      addFlag: false,
      demandPlans: [],
      demandPlanMap: {},
      // 下拉框map
      typeMap: {},
      reportTypeMap: {},
      periodTypeMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_TYPE)
    this.reportTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPORT_RANK)
    this.periodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_PERIOD_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_PLAN_STATUS)
    queryPurchaseDemandPlan({ projectId: this.$store.getters.userInfo.projectId, status: this.DictCache.VALUE.PURCHASE_DEMAND_PLAN_STATUS.PURCHASE_DEMAND_PLAN_STATUS_YWC }).then(res => {
      this.demandPlans = res.data
      this.demandPlans.forEach((item) => {
        this.demandPlanMap[item.id] = item
      })
    })
  },
  methods: {
    base (record) {
      this.BaseTool.ListForm.clearOneList(this)
      this.visible = true
      const modal = this.$refs.planList
      const { form: { setFieldsValue } } = this
      // 用于明细选择
      this.$store.dispatch('setDemandPlanId', null)
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.addFlag = true
        this.modalTitle = '添加采购计划'
        this.$store.dispatch('setPurchaseType', 1)
        setFieldsValue({
          'year': new Date().getFullYear(),
          'periodValue': new Date().getMonth() + 1
        })
        modal.base('-1')
        return
      }
      this.addFlag = false
      // 用于明细选择
      this.$store.dispatch('setDemandPlanId', record.demandPlanId)
      this.$store.dispatch('setPurchaseType', record.type)
      modal.base(record.id)
      this.addFlag = false
      this.modalTitle = '编辑采购计划'
      // 日期处理
      record.planDate = this.BaseTool.Moment(record.planDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.demandDate = this.BaseTool.Moment(record.demandDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'billNo',
          'demandPlanId',
          'demandPlanName',
          'companyId',
          'companyName',
          'projectId',
          'name',
          'projectName',
          'type',
          'planDate',
          'reportType',
          'demandDate',
          'item',
          'year',
          'periodValue',
          'periodType',
          'summary',
          'specialDescription',
          'money',
          'usedMoney',
          'progress',
          'quantity',
          'boughtQuantity',
          'arrivedQuantity',
          'notArriveQuantity',
          'totalWeight',
          'totalVolume',
          'refuseReason',
          'applyTime',
          'auditTime',
          'status',
          'remark',
          'delFlag'
        ])))
      })
    },
    save (value) {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期处理
        values.submitType = value
        values.planDate = this.BaseTool.Date.formatter(values.planDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.demandDate = this.BaseTool.Date.formatter(values.demandDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.BaseTool.ListForm.setOneListValues(this, values)
        if (this.addFlag) {
          addPurchasePlan(values)
            .then((res) => {
              if (!res.data) {
                this.$error({
                  title: '采购计划金额超过总需求计划预算',
                  content: '采购计划金额超过总需求计划预算，请先执行增补总金额签批程序,再进行采购计划操作，该采购计划暂时保存'
                })
              }
              this.BaseTool.ListForm.clearOneList(this)
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchasePlan(values)
            .then((res) => {
              if (!res.data) {
                this.$error({
                  title: '采购计划金额超过总需求计划预算',
                  content: '采购计划金额超过总需求计划预算，请先执行增补总金额签批程序,再进行采购计划操作，该采购计划暂时保存'
                })
              }
              this.BaseTool.ListForm.clearOneList(this)
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    changePlan (value) {
      const item = this.demandPlanMap[value]
      const { form: { setFieldsValue } } = this
      if (!item.regionId) {
        const newMap = {}
        for (const key in this.reportTypeMap) {
          if (key !== '30') {
            newMap[key] = this.reportTypeMap[key]
          }
        }
        this.reportTypeMap = newMap
      }
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'projectId': item.projectId,
          'projectName': item.projectName,
          'companyId': item.companyId,
          'companyName': item.companyName,
          'reportType': null,
          'type': item.type
        }))
      })
      this.generateName()
      // 用于明细选择
      this.$store.dispatch('setDemandPlanId', value)
    },
    generateName () {
      this.$nextTick(() => {
        const { form: { getFieldValue, setFieldsValue } } = this
        const projectName = getFieldValue('projectName')
        const type = getFieldValue('type')
        if (projectName && type) {
          const year = getFieldValue('year')
          // const periodValue = getFieldValue('periodValue')
          // const periodType = getFieldValue('periodType')
          let name = ''
          if (year) {
            name += (year + '年')
          }
          // if (periodValue && periodType) {
          //   name += (periodValue + this.periodTypeMap[periodType])
          // }
          name += (projectName + this.typeMap[type] + '采购计划')
          setFieldsValue({
            'name': name
          })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
