<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_APPLY_STATUS.PURCHASE_APPLY_STATUS_DSH)">
            <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-input v-decorator="['demandPlanId']" 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="['purchasePlanId', {rules: [{required: true, message: '采购计划不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="item in purchasePlans"
                :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="disableFlag"-->
        <!--              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-select
              v-decorator="['reportType', {rules: [{required: true, message: '呈报不能为空'}]}]"
              @change="changeReportType"
              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-select
              v-decorator="['purchaserId']"
              placeholder="请选择">
              <a-select-option
                v-for="item in users"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId">{{ item.realName }}
              </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-checkbox
              v-decorator="[ 'contractFlag', { valuePropName: 'checked',initialValue: false, }]" >
            </a-checkbox>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="是否需要发运"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-checkbox
              @change="changeDispatchFlag"
              v-decorator="[ 'dispatchFlag', { valuePropName: 'checked',initialValue: false, }]" >
            </a-checkbox>
          </a-form-item>
        </row-item>

        <row-item>

          <a-form-item
            label="是否需要集装箱"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-checkbox
              :disabled="!dispatchFlag"
              v-decorator="[ 'containerFlag', { valuePropName: 'checked',initialValue: false, }]" >
            </a-checkbox>
          </a-form-item>
        </row-item>

        <row-item>

          <a-form-item
            label="是否需要陆运"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-checkbox
              :disabled="!dispatchFlag"
              v-decorator="[ 'landFlag', { valuePropName: 'checked',initialValue: false, }]" >
            </a-checkbox>
          </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-list>
    </a-form>
    <title-divider title="申请明细" width="90px"></title-divider>
    <purchase-apply-list ref="applyList"/>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchaseApply, updatePurchaseApply } from '@/api/purchase/purchase-apply'
import PurchaseApplyList from '../PurchaseApplyList'
import { queryPurchasePlan } from '@/api/purchase/purchase-plan'
import { queryProjectRole } from '@/api/upms/user'

export default {
  name: 'BasePurchaseApply',
  components: { PurchaseApplyList },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      dispatchFlag: false,
      addFlag: false,
      purchasePlans: [],
      purchasePlanMap: {},
      userMap: {},
      users: [],
      disableFlag: true,
      // 下拉框map
      typeMap: {},
      reportTypeMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    // const reportTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPORT_RANK)
    // const viceProjectId = this.$store.getters.userInfo.viceProjectId
    // if (viceProjectId) {
    //   const map = {}
    //   for (const key in reportTypeMap) {
    //     if (key < '20') {
    //       map[key] = reportTypeMap[key]
    //     }
    //   }
    //   this.reportTypeMap = map
    // } else {
    //   this.reportTypeMap = reportTypeMap
    // }
    this.reportTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPORT_RANK)
    queryPurchasePlan({ projectId: this.$store.getters.userInfo.projectId, status: this.DictCache.VALUE.PURCHASE_PLAN_STATUS.PURCHASE_PLAN_STATUS_YWC }).then(res => {
      this.purchasePlans = res.data
      this.purchasePlans.forEach((item) => {
        this.purchasePlanMap[item.id] = item
      })
    })
  },
  methods: {
    base (record) {
      this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_APPLY_TYPE)
      this.disableFlag = true
      this.BaseTool.ListForm.clearOneList(this)
      this.visible = true
      const modal = this.$refs.applyList
      const { form: { setFieldsValue } } = this
      // 用于明细选择
      this.$store.dispatch('setPurchasePlanId', null)
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.addFlag = true
        this.modalTitle = '添加采购申请'
        this.$store.dispatch('setAddFlag', true)
        modal.base('-1')
        return
      }
      // 用于明细选择
      this.$store.dispatch('setPurchasePlanId', record.purchasePlanId)
      this.$store.dispatch('setAddFlag', false)
      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.dispatchFlag = record.dispatchFlag
      this.getUsers(record.projectId)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'billNo',
          'demandPlanId',
          'purchasePlanId',
          'companyId',
          'companyName',
          'projectId',
          'projectName',
          'type',
          'planDate',
          'purchaserId',
          'reportType',
          'demandDate',
          'dispatchFlag',
          'contractFlag',
          'landFlag',
          'containerFlag',
          'item',
          'summary',
          'specialDescription',
          'money',
          'paidMoney',
          'quantity',
          'boughtQuantity',
          'arrivedQuantity',
          'notArriveQuantity',
          'totalWeight',
          'totalVolume',
          'refuseReason',
          'applyTime',
          'auditTime',
          'status',
          'remark',
          'delFlag'
        ])))
      })
    },
    getUsers (deptId) {
      queryProjectRole({ deptId: deptId,
        roleCodes: [this.DictCache.VALUE.ROLE_CODE.XMB_CGY,
          this.DictCache.VALUE.ROLE_CODE.FGS_CGY, this.DictCache.VALUE.ROLE_CODE.QYZB_CGY, this.DictCache.VALUE.ROLE_CODE.JT_CGY] }).then(res => {
        this.users = res.data
        const map = {}
        this.users.forEach((item) => {
          map[item.userId] = item
        })
        this.userMap = map
      })
    },
    changeDispatchFlag (e) {
      const value = e.target.checked
      this.dispatchFlag = value
      if (!value) {
        const { form: { setFieldsValue } } = this
        this.$nextTick(() => {
          setFieldsValue({
            landFlag: false,
            containerFlag: false
          })
        })
      }
    },
    changeReportType (value) {
      const { form: { setFieldsValue } } = this
      this.dispatchFlag = value >= this.DictCache.VALUE.REPORT_RANK.REPORT_RANK_FGS
      this.$nextTick(() => {
        setFieldsValue({
          dispatchFlag: this.dispatchFlag,
          landFlag: this.dispatchFlag,
          containerFlag: value > this.DictCache.VALUE.REPORT_RANK.REPORT_RANK_FGS
        })
      })
    },
    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)
        const purchaserId = values.purchaserId
        if (purchaserId) {
          values.purchaserName = this.userMap[purchaserId].realName
        }
        this.BaseTool.ListForm.setOneListValues(this, values)
        if (this.addFlag) {
          addPurchaseApply(values)
            .then((res) => {
              if (!res.data) {
                this.$error({
                  title: '采购申请金额超过总需求计划预算',
                  content: '采购申请金额超过总需求计划预算，请先执行增补总金额签批程序,再进行采购申请操作，该采购申请暂时保存'
                })
              }
              this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchaseApply(values)
            .then((res) => {
              if (!res.data) {
                this.$error({
                  title: '采购申请金额超过总需求计划预算',
                  content: '采购申请金额超过总需求计划预算，请先执行增补总金额签批程序,再进行采购申请操作，该采购申请暂时保存'
                })
              }
              this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    changePlan (value) {
      const item = this.purchasePlanMap[value]
      const { form: { setFieldsValue } } = this
      // const type = item.type
      // if (type === DictCache.VALUE.PURCHASE_TYPE.PURCHASE_TYPE_WZL) {
      //   this.disableFlag = false
      //   const typeMap = this.typeMap
      //   const newMap = {}
      //   Object.keys(typeMap).forEach((key) => {
      //     if (key >= 20 && key < 30) {
      //       newMap[key] = typeMap[key]
      //     }
      //   })
      //   this.typeMap = newMap
      // }
      if (!item.regionId) {
        const newMap = {}
        for (const key in this.reportTypeMap) {
          if (key !== '30') {
            newMap[key] = this.reportTypeMap[key]
          }
        }
        this.reportTypeMap = newMap
        this.getUsers(item.projectId)
      }
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'projectId': item.projectId,
          'projectName': item.projectName,
          'reportType': null,
          'demandPlanId': item.demandPlanId,
          'companyId': item.companyId,
          'companyName': item.companyName
        }))
      })
      this.$store.dispatch('setPurchasePlanId', value)
      this.$store.dispatch('setPurchaseType', item.type)
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
