<template>
  <a-card :bordered="false" :title="modalTitle" v-show="visible">
    <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_DEMAND_PLAN_STATUS.PURCHASE_DEMAND_PLAN_STATUS_SHE)">
            <a-button type="danger">提交审批</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()">下一步</a-button>
          <a-button style="margin-left: 8px" v-show="currentTab=== 2" type="primary" @click="save()">保存</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-form-item>

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

          <a-form-item
            label="公司名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['companyId', { rules: [{required: true, message: '公司不能为空'}]}]"
              placeholder="请选择"
              @change="changeCompany"
            >
              <a-select-option
                v-for="item in companies"
                :key="item.deptId"
                :label="item.name"
                :value="item.deptId">{{ 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-select
              v-decorator="['projectId', { rules: [{required: true, message: '项目不能为空'}]}]"
              placeholder="请选择"
              @change="changeProject"
            >
              <a-select-option
                v-for="item in projects"
                :key="item.deptId"
                :label="item.name"
                :value="item.deptId">{{ 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-select
              v-decorator="['type', {initialValue: 10,rules: [{required: true, message: '类别不能为空'}]}]"
              @change="changeType"
              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
              disabled="disabled"
              v-decorator="['name', {rules: [{required: true, message: '名称不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item v-if="currentTab!== 0">

          <a-form-item
            label="计划明细控制总额"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              disabled="disabled"
              style="width: 100%"
              :min="0"
              :step="0.01"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['planListControlMoney']"/>
          </a-form-item>
        </row-item>
        <row-item v-if="currentTab!== 0">

          <a-form-item
            label="计划明细总额"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              disabled="disabled"
              style="width: 100%"
              :min="0"
              :step="0.01"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['planListMoney']"/>
          </a-form-item>
        </row-item>
        <row-item v-if="currentTab!== 0">

          <a-form-item
            label="资金预算"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              style="width: 100%"
              :min="0"
              :step="0.01"
              :formatter="BaseTool.Amount.formatter"
              :parser="BaseTool.Amount.parser"
              v-decorator="['planMoney', {initialValue:1, 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-number-->
        <!--              style="width: 100%"-->
        <!--              :min="0"-->
        <!--              :step="0.01"-->
        <!--              :formatter="BaseTool.Amount.formatter"-->
        <!--              :parser="BaseTool.Amount.parser"-->
        <!--              v-decorator="['usedMoney']"/>-->
        <!--          </a-form-item>-->
        <!--        </row-item>-->
        <!--        <row-item>-->

        <!--          <a-form-item-->
        <!--            label="进度"-->
        <!--            :labelCol="BaseTool.Constant.labelCol"-->
        <!--            :wrapperCol="BaseTool.Constant.wrapperCol"-->
        <!--          >-->
        <!--            <a-input-->
        <!--              type="number"-->
        <!--              suffix="%"-->
        <!--              v-decorator="['progress']"/>-->
        <!--          </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-demand-plan-list ref="purchaseDemandPlanList" v-show="currentTab=== 1 || currentTab=== 2" @ok="updateMoney"></purchase-demand-plan-list>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchaseDemandPlan, updatePurchaseDemandPlan, getMoney } from '@/api/purchase/purchase-demand-plan'
import { queryDept } from '@/api/upms/dept'
import PurchaseDemandPlanList from '../PurchaseDemandPlanList'

export default {
  name: 'BasePurchaseDemandPlan',
  components: { PurchaseDemandPlanList },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      addFlag: false,
      user: this.$store.getters.userInfo,
      companies: [],
      money: 0,
      saveFlag: false,
      currentTab: 0,
      id: '-1',
      projects: [],
      projectMap: [],
      // 下拉框map
      typeMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_TYPE)
    queryDept({ nature: 'FEN_GONG_SI' }).then(res => {
      this.companies = res.data
    })
  },
  methods: {
    base (record) {
      this.form.resetFields()
      this.currentTab = 0
      this.BaseTool.ListForm.clearOneList(this)
      this.visible = true
      const { form: { setFieldsValue } } = this
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.$store.dispatch('setPurchaseType', 10)
        this.$store.dispatch('setAddFlag', true)
        this.addFlag = true
        this.modalTitle = '添加总需求计划'
        this.getProjects(this.user.companyId)
        // 日期处理
        this.$nextTick(() => {
          setFieldsValue({
            type: this.type,
            companyId: this.user.companyId,
            projectId: this.user.projectId
          })
        })
        return
      }
      this.$store.dispatch('setPurchaseType', record.type)
      this.$store.dispatch('setAddFlag', false)
      this.id = record.id
      this.addFlag = false
      this.modalTitle = '编辑总需求计划'
      this.getProjects(record.companyId)
      this.money = record.planMoney
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'name',
          'companyId',
          'companyName',
          'projectId',
          'projectName',
          'type',
          'planMoney',
          'usedMoney',
          'planListMoney',
          'planListControlMoney',
          'progress',
          'quantity',
          'boughtQuantity',
          'arrivedQuantity',
          'notArriveQuantity',
          'status',
          'remark',
          'delFlag'
        ])))
      })
    },
    viewList (id) {
      this.$nextTick(() => {
        const modal = this.$refs.purchaseDemandPlanList
        modal.base(id)
      })
    },
    changeCompany (value) {
      this.getProjects(value)
    },
    changeProject (value) {
      this.generateName()
    },
    changeType (value) {
      this.$store.dispatch('setPurchaseType', value)
      this.generateName()
    },
    getProjects (value) {
      queryDept({ nature: 'XIANG_MU_BU', parentId: value }).then(res => {
        this.projects = res.data
        this.projects.forEach((item) => {
          this.projectMap[item.deptId] = item.name
        })
      })
    },
    generateName () {
      this.$nextTick(() => {
        const { form: { getFieldValue, setFieldsValue } } = this
        const projectId = getFieldValue('projectId')
        const type = getFieldValue('type')
        if (projectId && type) {
          const name = this.projectMap[projectId] + this.typeMap[type] + '总需求计划'
          setFieldsValue({
            'name': name
          })
        }
      })
    },
    next () {
      if (this.currentTab === 0) {
        this.save()
      } else {
        this.currentTab += 1
      }
      if (this.currentTab === 2) {
        this.updateMoney()
      }
    },
    prev () {
      this.currentTab -= 1
    },
    save (value) {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          console.log(errors)
          this.confirmLoading = false
          return
        }
        this.BaseTool.ListForm.setOneListValues(this, values)
        values.submitType = value
        // 日期处理
        if (this.addFlag) {
          addPurchaseDemandPlan(values)
            .then((res) => {
              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',
                  'name',
                  'companyId',
                  'companyName',
                  'projectId',
                  'projectName',
                  'type',
                  'planMoney',
                  'usedMoney',
                  'planListMoney',
                  'planListControlMoney',
                  'progress',
                  'quantity',
                  'boughtQuantity',
                  'arrivedQuantity',
                  'notArriveQuantity',
                  'status',
                  'remark',
                  'delFlag'
                ])))
              })
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchaseDemandPlan(values)
            .then(() => {
              if (this.currentTab === 2) {
                this.handleCancel({})
                return
              }
              this.currentTab += 1
              this.viewList(this.id)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$store.dispatch('setPurchaseType', null)
      this.BaseTool.ListForm.clearOneList(this)
      this.$emit('ok', values)
    },
    updateMoney () {
      getMoney(this.id).then(res => {
        const data = res.data
        const { form: { setFieldsValue } } = this
        const money = data.planListControlMoney
        this.$nextTick(() => {
          setFieldsValue({
            'planListControlMoney': money,
            'planListMoney': data.planListMoney,
            'planMoney': this.$store.getters.addFlag ? money : this.money
          })
        })
      })
    }

  }
}
</script>
