<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 v-show="currentTab=== 2" title="提交审批操作过后将无法更改，确认进行该操作吗？" @confirm="save(DictCache.VALUE.PURCHASE_PLAN_STATUS.PURCHASE_PLAN_STATUS_SHE)">
            <a-button type="danger" :loading="confirmLoading">提交审批</a-button>
          </a-popconfirm>
          <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()" :loading="confirmLoading">下一步</a-button>
          <a-button style="margin-left: 8px" v-show="currentTab=== 2" type="primary" @click="save()" :loading="confirmLoading">保存</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回列表</a-button>
        </span>
      </a-col>
    </a-row>
    <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-form :form="form" v-show="currentTab=== 0 || currentTab=== 2">

      <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-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-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
              suffix="%"
              v-decorator="['quantityRatio', {initialValue: 100, 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="['remark']"/>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <title-divider v-show="currentTab=== 2" title="计划明细" width="90px"></title-divider>
    <purchase-plan-list-step ref="planList" v-show="currentTab=== 1 || currentTab=== 2"/>
  </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 PurchasePlanListStep from '../PurchasePlanListStep'

export default {
  name: 'BasePurchasePlan',
  components: { PurchasePlanListStep },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      currentTab: 0,
      id: '-1',
      rate: 100,
      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.currentTab = 0
      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.$store.dispatch('setDemandPlanId', record.demandPlanId)
      this.$store.dispatch('setPurchaseType', record.type)
      this.id = record.id
      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',
          'quantityRatio',
          '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'
        ])))
      })
    },
    next () {
      if (this.currentTab === 0) {
        this.save()
      } else {
        if (this.currentTab === 1) {
          this.$refs.planList.updateList()
        }
        this.currentTab += 1
      }
    },
    prev () {
      if (this.currentTab === 1) {
        this.$refs.planList.updateList()
      }
      this.currentTab -= 1
    },
    viewList (id) {
      this.$nextTick(() => {
        const modal = this.$refs.planList
        modal.base(id)
      })
    },
    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) {
          this.$message.info('此操作会初始化计划明细内容，需要花费点时间，请耐心等待', 10)
          addPurchasePlan(values)
            .then((res) => {
              if (!res.data.flag) {
                this.$error({
                  title: '采购计划金额超过总需求计划预算',
                  content: '采购计划金额超过总需求计划预算，请先执行增补总金额签批程序,再进行采购计划操作，该采购计划暂时保存'
                })
              }
              this.currentTab += 1
              this.viewList(res.data.id)
              this.id = res.data.id
              this.addFlag = false
              const { form: { setFieldsValue } } = this
              this.$nextTick(() => {
                setFieldsValue(Object.assign(pick(res.data, [
                  'id',
                  'billNo',
                  'demandPlanId',
                  'demandPlanName',
                  'companyId',
                  'companyName',
                  'projectId',
                  'quantityRate',
                  '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'
                ])))
              })
              // this.BaseTool.ListForm.clearOneList(this)
              // this.handleCancel(values)
              this.confirmLoading = false
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchasePlan(values)
            .then((res) => {
              if (!res.data) {
                this.$error({
                  title: '采购计划金额超过总需求计划预算',
                  content: '采购计划金额超过总需求计划预算，请先执行增补总金额签批程序,再进行采购计划操作，该采购计划暂时保存'
                })
              }
              if (this.currentTab === 2) {
                this.handleCancel({})
                return
              }
              this.currentTab += 1
              this.viewList(this.id)
              this.confirmLoading = false
            }).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')
          let name = ''
          if (year) {
            name += (year + '年')
          }
          name += (projectName + this.typeMap[type] + '采购计划')
          setFieldsValue({
            'name': name
          })
        }
      })
    },
    handleCancel (values) {
      if (this.currentTab === 1) {
        this.$refs.planList.updateList()
      }
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
