<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-button v-show="currentTab!== 0" style="margin-left: 8px" @click="prev()">上一步</a-button>
          <a-button style="margin-left: 8px" v-show="currentTab!== 1" type="primary" @click="next()">下一步</a-button>
          <a-button style="margin-left: 8px" v-show="currentTab=== 1" type="primary" @click="save()">保存</a-button>
          <a-popconfirm
            style="margin-left: 8px"
            v-show="currentTab=== 1"
            title="初验完成操作过后将无法更改，确认进行该操作吗？"
            @confirm="save(record.containerFlag ? DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DZX : DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRK)">
            <a-button type="danger">初验完成</a-button>
          </a-popconfirm>
          <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-steps>
    <title-divider title="基本信息" width="90px" v-show="currentTab=== 2"></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>

      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">

          <a-form-item
            label="发运单号"
          >
            <a-input
              :disabled="!addFlag"
              v-decorator="['billNo']"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="发运日期"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['dispatchDate', {rules: [{required: true, message: '发货日期不能为空'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="采购员"
          >
            <a-select
              mode="multiple"
              @change="changeCgy"
              v-decorator="['purchaserId', {rules: [{required: true, message: '采购员不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="item in cgy"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId">{{ item.realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">

          <a-form-item
            label="采购员联系方式"
          >
            <a-input
              disabled="disabled"
              v-decorator="['purchaserPhone', {rules: [{required: true, message: '采购员联系方式不能为空'}]}]"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="发货员"
          >
            <a-select
              @change="changeFhy"
              v-decorator="['shipperId', {rules: [{required: true, message: '发货员不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="item in fhy"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId">{{ item.realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="发货员联系方式"
          >
            <a-input
              disabled="disabled"
              v-decorator="['shipperPhone']"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">
          <a-form-item
            label="始发地国家"
          >
            <a-select
              disabled="disabled"
              v-decorator="['originCountryId']"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in countryMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item
            label="始发地地址"
          >
            <a-input
              disabled="disabled"
              v-decorator="['originCountryAddress']"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item
            label="收货员"
          >
            <a-select
              @change="changeShy"
              v-decorator="['receiverId']"
              placeholder="请选择">
              <a-select-option
                v-for="item in shy"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId">{{ item.realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">
          <a-form-item
            label="收货员联系方式"
          >
            <a-input
              v-decorator="['receiverPhone']"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="目的地国家"
          >
            <a-select
              disabled="disabled"
              v-decorator="['destinationCountryId']"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in countryMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">

          <a-form-item
            label="目的地地址"
          >
            <a-input
              disabled="disabled"
              v-decorator="['destinationCountryAddress']"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row class="form-row" :gutter="16">
        <a-col :lg="7" :md="12" :sm="24">

          <a-form-item
            label="货运方式"
          >
            <a-select
              v-decorator="['dispatchType', {rules: [{required: true, message: '货运方式不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in dispatchTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item
            label="存货位置"
          >
            <a-select
              @change="changeInventoryLocation"
              v-decorator="['inventoryLocation']"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in storePlaceMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>

        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24">
          <a-form-item
            label="发运港"
          >
            <a-input
              v-decorator="['dispatchPort']"/>
          </a-form-item>

        </a-col>
      </a-row>
    </a-form>
    <!--    <title-divider title="关联采购单" v-show="currentTab=== 2" width="90px"></title-divider>-->
    <!--    <purchase-dispatch-order-list ref="list"/>-->
    <purchase-order-dispatch-order ref="order" v-show="currentTab=== 1"/>
    <title-divider title="发运明细" v-show="currentTab=== 1" width="90px"></title-divider>
    <purchase-dispatch-order-list ref="list" v-show="currentTab=== 1"/>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchaseDispatchOrder, updatePurchaseDispatchOrder } from '@/api/purchase/purchase-dispatch-order'
import PurchaseDispatchOrderList from '@/views/purchase/purchase-dispatch-order-list/PurchaseDispatchOrderListForAdd'
import PurchaseOrderDispatchOrder from '@/views/purchase/purchase-dispatch-order/PurchaseOrderDispatchOrder'
import PurchaseOrderSelectModal from '@/views/purchase/purchase-order/modules/PurchaseOrderSelectModal'
import { queryDeptChildrenRoleUser } from '@/api/upms/user'

export default {
  name: 'BasePurchaseDispatchOrderChoose',
  components: { PurchaseDispatchOrderList, PurchaseOrderSelectModal, PurchaseOrderDispatchOrder },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      addFlag: false,
      userId: this.$store.getters.userInfo.userId,
      // 下拉框map
      cgy: [],
      cgyMap: {},
      fhy: [],
      fhyMap: {},
      id: '-1',
      record: {},
      currentTab: 0,
      shy: [],
      countryMap: {},
      shyMap: {},
      dispatchTypeMap: {},
      storePlaceMap: {}

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.dispatchTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.DISPATCH_TYPE)
    this.countryMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_COUNTRY)
    this.storePlaceMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_STORE_PLACE)
    queryDeptChildrenRoleUser({ 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.cgy = res.data
      const cgyMap = {}
      this.cgy.forEach((item) => {
        cgyMap[item.userId] = item
      })
      this.cgyMap = cgyMap
    })
    queryDeptChildrenRoleUser({ roleCodes: [this.DictCache.VALUE.ROLE_CODE.XMB_FHY, this.DictCache.VALUE.ROLE_CODE.FGS_FHY,
      this.DictCache.VALUE.ROLE_CODE.QYZB_FHY, this.DictCache.VALUE.ROLE_CODE.JT_FHY] }).then(res => {
      this.fhy = res.data
      const fhyMap = {}
      this.fhy.forEach((item) => {
        fhyMap[item.userId] = item
      })
      this.fhyMap = fhyMap
    })
    queryDeptChildrenRoleUser({ roleCodes: [this.DictCache.VALUE.ROLE_CODE.XMB_SHY, this.DictCache.VALUE.ROLE_CODE.FGS_SHY,
      this.DictCache.VALUE.ROLE_CODE.QYZB_SHY, this.DictCache.VALUE.ROLE_CODE.JT_SHY] }).then(res => {
      this.shy = res.data
      const shyMap = {}
      this.shy.forEach((item) => {
        shyMap[item.userId] = item
      })
      this.shyMap = shyMap
    })
  },
  methods: {
    base (record) {
      this.BaseTool.ListForm.clearOneList(this)
      this.visible = true
      this.currentTab = 0
      const { form: { setFieldsValue } } = this
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加发运单'
        this.addFlag = true
        this.id = '-1'
        this.$store.dispatch('setAddFlag', true)
        this.$nextTick(() => {
          let user = this.cgyMap[this.userId]
          if (user) {
            this.changeCgy([this.userId])
          }
          user = this.fhyMap[this.userId]
          if (user) {
            this.changeFhy(this.userId)
          }
          user = this.shyMap[this.userId]
          if (user) {
            this.changeShy(this.userId)
          }
        })
        this.$store.dispatch('setInventoryLocation', null)
        return
      }
      this.addFlag = false
      this.modalTitle = '编辑发运单'
      this.$store.dispatch('setAddFlag', false)
      this.record = record
      this.id = record.id
      // 日期处理
      record.dispatchDate = this.BaseTool.Moment(record.dispatchDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.purchaserId = record.purchaserId ? record.purchaserId.split(',') : []
      this.$store.dispatch('setInventoryLocation', record.inventoryLocation)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'billNo',
          'purchaseApplyId',
          'purchasePlanId',
          'demandPlanId',
          'purchaseOrderIds',
          'orderNos',
          'companyId',
          'companyName',
          'projectId',
          'projectName',
          'type',
          'dispatchDate',
          'originCountryId',
          'originCountryName',
          'originCountryAddress',
          'destinationCountryId',
          'destinationCountryName',
          'dispatchPort',
          'destinationCountryAddress',
          'purchaserId',
          'purchaserName',
          'purchaserPhone',
          'shipperId',
          'shipperName',
          'shipperPhone',
          'receiverId',
          'receiverName',
          'receiverPhone',
          'inventoryLocation',
          'dispatchType',
          'quantity',
          'dispatchedQuantity',
          'notDispatchQuantity',
          'mailingNum',
          'freightFee',
          'insuranceFee',
          'dispatchSurcharge',
          'tariff',
          'clearanceCharge',
          'portSurcharge',
          'customsDeclaration',
          'proformaInvoice',
          'freightFeeType',
          'insuranceFeeType',
          'dispatchSurchargeType',
          'tariffType',
          'clearanceChargeType',
          'portSurchargeType',
          'secondaryTransportationFeeType',
          'secondaryTransportationFee',
          'differenceType',
          'warehouseId',
          'warehouseName',
          'enterReason',
          'status',
          'remark',
          'delFlag'
        ])))
      })
    },
    changeInventoryLocation (value) {
      this.$store.dispatch('setInventoryLocation', value)
    },
    viewList (record) {
      this.$nextTick(() => {
        const modal = this.$refs.order
        modal.base(record.id)
        this.$refs.list.base(record)
      })
    },
    next () {
      if (this.currentTab === 0) {
        this.save()
      } else {
        if (this.currentTab === 1) {
          this.$refs.list.updateNewest()
        }
        this.currentTab += 1
      }
      // this.$refs.order.changeEndFlag(this.currentTab === 1)
    },
    prev () {
      if (this.currentTab === 1) {
        this.$refs.list.updateNewest()
      }
      this.currentTab -= 1
    },
    save (value) {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.submitType = value
        values.dispatchDate = this.BaseTool.Date.formatter(values.dispatchDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.purchaserId = values.purchaserId ? values.purchaserId.join(',') : ''
        this.BaseTool.ListForm.setOneListValues(this, values)
        if (this.addFlag) {
          addPurchaseDispatchOrder(values)
            .then((res) => {
              this.currentTab += 1
              const record = res.data
              this.viewList(record)
              this.id = record.id
              this.addFlag = false
              // 日期处理
              record.dispatchDate = this.BaseTool.Moment(record.dispatchDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
              const { form: { setFieldsValue } } = this
              this.$nextTick(() => {
                record.purchaserId = record.purchaserId ? record.purchaserId.split(',') : []
                setFieldsValue(Object.assign(pick(record, [
                  'id',
                  'billNo',
                  'purchaseApplyId',
                  'purchasePlanId',
                  'demandPlanId',
                  'purchaseOrderIds',
                  'orderNos',
                  'companyId',
                  'companyName',
                  'projectId',
                  'projectName',
                  'type',
                  'dispatchDate',
                  'originCountryId',
                  'originCountryName',
                  'originCountryAddress',
                  'destinationCountryId',
                  'destinationCountryName',
                  'destinationCountryAddress',
                  'purchaserId',
                  'purchaserName',
                  'purchaserPhone',
                  'shipperId',
                  'shipperName',
                  'shipperPhone',
                  'receiverId',
                  'receiverName',
                  'receiverPhone',
                  'inventoryLocation',
                  'dispatchType',
                  'quantity',
                  'dispatchedQuantity',
                  'notDispatchQuantity',
                  'mailingNum',
                  'freightFee',
                  'insuranceFee',
                  'dispatchSurcharge',
                  'tariff',
                  'clearanceCharge',
                  'portSurcharge',
                  'customsDeclaration',
                  'proformaInvoice',
                  'freightFeeType',
                  'insuranceFeeType',
                  'dispatchSurchargeType',
                  'tariffType',
                  'clearanceChargeType',
                  'portSurchargeType',
                  'secondaryTransportationFeeType',
                  'secondaryTransportationFee',
                  'differenceType',
                  'warehouseId',
                  'warehouseName',
                  'enterReason',
                  'status',
                  'remark',
                  'delFlag'
                ])))
              }).catch(() => {
                this.confirmLoading = false
              })
            })
        } else {
          updatePurchaseDispatchOrder(values)
            .then(() => {
              if (this.currentTab === 1) {
                this.handleCancel({})
                return
              }
              this.currentTab += 1
              this.viewList(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    changeCgy (value) {
      const { form: { setFieldsValue } } = this
      const phone = []
      if (value.length > 0) {
        value.forEach(item => {
          phone.push(this.cgyMap[item].phone)
        })
      }
      setFieldsValue({
        purchaserPhone: phone.join(','),
        purchaserId: value
      })
    },
    changeFhy (value) {
      const { form: { setFieldsValue } } = this
      const user = this.fhyMap[value]
      setFieldsValue({
        shipperPhone: user.phone,
        originCountryId: user.country,
        shipperId: value,
        originCountryAddress: user.addressDetail
      })
    },
    changeShy (value) {
      const { form: { setFieldsValue } } = this
      const user = this.shyMap[value]
      setFieldsValue({
        receiverPhone: user.phone,
        destinationCountryId: user.country,
        receiverId: value,
        destinationCountryAddress: user.addressDetail
      })
    },
    handleCancel (values) {
      if (this.currentTab === 1) {
        this.$refs.list.updateNewest()
      }
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
