<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 title="提交审批操作过后将无法更改，确认进行该操作吗？" @confirm="save(DictCache.VALUE.PURCHASE_DEMAND_PLAN_STATUS.PURCHASE_DEMAND_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-form-item>

      <row-list :col="2">
        <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>

          <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-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>

          <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>

          <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', {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 title="需求明细" width="90px"></title-divider>
    <purchase-demand-plan-list ref="purchaseDemandPlanList" @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,
      companies: [],
      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.BaseTool.ListForm.clearOneList(this)
      this.visible = true
      const { form: { setFieldsValue } } = this
      const modal = this.$refs.purchaseDemandPlanList
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.$store.dispatch('setPurchaseType', 10)
        this.$store.dispatch('setAddFlag', true)
        this.addFlag = true
        this.modalTitle = '添加总需求计划'
        const id = this.BaseTool.String.uuid()
        this.id = id
        // 日期处理
        this.$nextTick(() => {
          setFieldsValue({
            id: id,
            type: this.type
          })
        })
        modal.base(id)
        return
      }
      this.$store.dispatch('setPurchaseType', record.type)
      this.$store.dispatch('setAddFlag', false)
      modal.base(record.id)
      this.id = record.id
      this.addFlag = false
      this.modalTitle = '编辑总需求计划'
      this.getProjects(record.companyId)
      // 日期处理
      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'
        ])))
      })
    },
    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')
        console.log(projectId)
        console.log(type)
        if (projectId && type) {
          const name = this.projectMap[projectId] + this.typeMap[type] + '总需求计划'
          setFieldsValue({
            'name': name
          })
        }
      })
    },
    save (value) {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        this.BaseTool.ListForm.setOneListValues(this, values)
        values.submitType = value
        // 日期处理
        if (this.addFlag) {
          addPurchaseDemandPlan(values)
            .then(() => {
              this.handleCancel(values)
              this.$store.dispatch('setPurchaseType', null)
              this.BaseTool.ListForm.clearOneList(this)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchaseDemandPlan(values)
            .then(() => {
              this.handleCancel(values)
              this.$store.dispatch('setPurchaseType', null)
              this.BaseTool.ListForm.clearOneList(this)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    },
    updateMoney () {
      getMoney(this.id).then(res => {
        const data = res.data
        const { form: { setFieldsValue } } = this
        setFieldsValue({
          'planListControlMoney': data.planListControlMoney,
          'planMoney': data.planListControlMoney,
          'planListMoney': data.planListMoney
        })
      })
    }

  }
}
</script>
