<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-button 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="['purchaseOrderId']" type="hidden"/>
        <a-input v-decorator="['sellerName']" 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
              v-decorator="['projectCode']"/>
          </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="['projectName', {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-input
              v-decorator="['supplierCode']"/>
          </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="['no']"/>
          </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="['signDate', {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-input
              v-decorator="['signAddress', {initialValue: '重庆市'}]"/>
          </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="['supplierId', {rules: [{required: true, message: '乙方不能为空'}]}]"
              @change="changeSupplier"
              placeholder="请选择">
              <a-select-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id">{{ item.name }}
              </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-textarea
              v-decorator="['sellerDeliveryAddress', {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-textarea
              v-decorator="['sellerUnitAddress', {rules: [{required: true, message: '甲方单位地址不能为空'}]}]"/>
          </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="['sellerPhone', {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-input
              v-decorator="['sellerTaxNo', {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-input
              v-decorator="['sellerBankName', {rules: [{required: true, message: '甲方开户银行不能为空'}]}]"/>
          </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="['sellerBankNo', {rules: [{required: true, message: '甲方帐号不能为空'}]}]"/>
          </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="['buyerName', {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-textarea
              v-decorator="['buyerDeliveryAddress', {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-textarea
              v-decorator="['buyerUnitAddress', {rules: [{required: true, message: '乙方单位地址'}]}]"/>
          </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="['buyerPhone', {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-input
              v-decorator="['buyerTaxNo', {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-input
              v-decorator="['buyerBankName', {rules: [{required: true, message: '乙方开户银行不能为空'}]}]"/>
          </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="['buyerBankNo', {rules: [{required: true, message: '甲方帐号不能为空'}]}]"/>
          </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="['moneyType', {initialValue: 1, rules: [{required: true, message: '金额类型不能为空'}]}]"
              disabled="disable"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in moneyTypeMap"
                :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
              type="number"
              suffix="工作日"
              v-decorator="['leadTime', {initialValue: 30,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-input
              v-decorator="['deliveryPlace', {initialValue: '国内指定港口'}]"/>
          </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
              type="number"
              suffix="日"
              v-decorator="['delayTime', {initialValue: 30}]"/>
          </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="changePayPeriod"
              v-decorator="['payPeriod', {initialValue: 1, rules: [{required: true, message: '付款周期类型不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in payPeriodTypeMap"
                :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="1期"
          >
            <a-input
              style="width:70%"
              v-decorator="['onePeriodName', {initialValue: onePeriodNameDefault}]"/>
            <a-input
              type="number"
              style="width:30%"
              suffix="%"
              v-decorator="['onePeriodRatio', {initialValue: onePeriodRatioDefault}]"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="form-row" :gutter="16" v-show="payPeriod > 1">
        <a-col :lg="7" :md="12" :sm="24" v-show="payPeriod > 1">
          <a-form-item
            label="2期"
          >
            <a-input
              style="width:70%"
              v-decorator="['twoPeriodName', {initialValue: twoPeriodNameDefault}]"/>
            <a-input
              type="number"
              style="width:30%"
              suffix="%"
              v-decorator="['twoPeriodRatio', {initialValue: twoPeriodRatioDefault}]"/>
          </a-form-item>
        </a-col>
        <a-col :xl="{span: 7, offset: 1}" :lg="{span: 8}" :md="{span: 12}" :sm="24" v-show="payPeriod > 2">
          <a-form-item
            label="3期"
          >
            <a-input
              style="width:70%"
              v-decorator="['threePeriodName', {initialValue: threePeriodNameDefault}]"/>
            <a-input
              type="number"
              style="width:30%"
              suffix="%"
              v-decorator="['threePeriodRatio', {initialValue: threePeriodRatioDefault}]"/>
          </a-form-item>
        </a-col>
      </a-row>

      <title-divider title="基本信息" width="90px"></title-divider>
      <purchase-contract-main-list ref="contractMainList"/>
      <title-divider title="合同模板" width="90px"></title-divider>
      <!--      <a-row class="form-row" :gutter="16">-->
      <!--        <a-col :lg="24" :md="24" :sm="24">-->
      <!--          <wang-editor-->
      <!--            :content="content"-->
      <!--            @catchData="catchData"-->
      <!--          ></wang-editor>-->
      <!--        </a-col>-->
      <!--      </a-row>-->
      <a-row class="form-row" :gutter="16">
        <a-col :lg="24" :md="24" :sm="24">
          <div style="width:794px">
            <UEditor :config="config" ref="ueditor"></UEditor>
          </div>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addPurchaseContract, updatePurchaseContract } from '@/api/purchase/purchase-contract'
import { configData } from '@/api/upms/config'
import { querySupplier } from '@/api/purchase/supplier'
import WangEditor from '@/components/Editor/WangEditor'
import PurchaseContractMainList from '../PurchaseContractMainList'
import UEditor from '@/components/Editor/Ueditor.vue'

export default {
  name: 'BasePurchaseContract',
  components: { WangEditor, PurchaseContractMainList, UEditor },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      content: '',
      // 下拉框map
      moneyTypeMap: {},
      payPeriodTypeMap: {},
      configMap: {},
      supplierMap: {},
      suppliers: [],
      payPeriod: 1,
      onePeriodNameDefaults: ['无预付款，货到付款', '预付款', '预付款'],
      onePeriodRatioDefaults: [100, 10, 30],
      twoPeriodNameDefaults: ['', '发货支付', '离岸后支付7个工作日'],
      twoPeriodRatioDefaults: [0, 90, 60],
      threePeriodNameDefaults: ['', '', '到港7个工作日内支付尾款'],
      threePeriodRatioDefaults: [0, 0, 10],
      onePeriodNameDefault: '无预付款，货到付款',
      onePeriodRatioDefault: 100,
      twoPeriodNameDefault: '',
      twoPeriodRatioDefault: 0,
      threePeriodNameDefault: '',
      threePeriodRatioDefault: 0,
      config: {
        // 可以在此处定义工具栏的内容
        // toolbars: [
        //  ['fullscreen', 'undo', 'redo','|','bold', 'italic', 'underline',
        //  '|','superscript','subscript','|', 'insertorderedlist', 'insertunorderedlist',
        //  '|','fontfamily','fontsize','justifyleft','justifyright','justifycenter','justifyjustify']
        // ],
        autoHeightEnabled: false,
        zIndex: 2,
        // autoFloatEnabled: true,
        initialContent: '请输入内容', // 初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
        autoClearinitialContent: true, // 是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
        initialFrameWidth: null,
        initialFrameHeight: 450,
        BaseUrl: '',
        UEDITOR_HOME_URL: '/ueditor/'
      }

    }
  },
  props: {},
  created () {
    // 下拉框map
    this.payPeriodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_CONTRACT_PAY_PERIOD)
    this.moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    configData().then(res => {
      this.configMap = res.data['config:open:value']
      console.log(this.configMap)
    })
  },
  methods: {
    base (record, order) {
      querySupplier({ purchaseOrderId: order.id }).then(res => {
        this.suppliers = res.data
        const map = {}
        this.suppliers.forEach((item) => {
          map[item.id] = item
        })
        this.supplierMap = map
        this.BaseTool.ListForm.clearOneList(this)
        this.BaseTool.ListForm.clearTwoList(this)
        this.visible = true
        const { form: { setFieldsValue } } = this
        const modal = this.$refs.contractMainList
        this.$store.dispatch('setPurchaseOrderId', order.id)
        this.$store.dispatch('setPurchaseType', order.type)
        // 如果是空标识添加
        if (this.BaseTool.Object.isBlank(record)) {
          this.payPeriod = 1
          this.$store.dispatch('setAddFlag', true)
          this.$store.dispatch('setPurchaseContractId', null)
          this.addFlag = true
          this.modalTitle = '添加合同'
          const info = this.configMap[this.DictCache.TYPE.GROUP_INFO + '_CN']
          console.log(info)
          const groupInfo = JSON.parse(info)
          this.$nextTick(() => {
            setFieldsValue({
              purchaseOrderId: order.id,
              moneyType: order.moneyType,
              projectCode: order.projectCode,
              projectName: order.projectName,
              buyerName: groupInfo.name,
              buyerDeliveryAddress: groupInfo.arriveAddress,
              buyerUnitAddress: groupInfo.unitAddress,
              buyerPhone: groupInfo.phone,
              buyerTaxNo: groupInfo.taxNo,
              buyerBankName: groupInfo.bankName,
              buyerBankNo: groupInfo.bankNo
            })
            this.$refs.ueditor.setContent(this.configMap['PURCHASE_CONTRACT_PEIJIAN'])
          })
          modal.base('-1')
          return
        }
        this.$store.dispatch('setPurchaseType', order.type)
        this.$store.dispatch('setPurchaseContractId', record.id)
        this.$store.dispatch('setAddFlag', false)
        modal.base(record.id)
        this.addFlag = false
        this.modalTitle = '编辑合同'
        record.signDate = this.BaseTool.Moment(record.signDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.payPeriod = record.payPeriod ? record.payPeriod : 1
        // 日期处理
        this.$nextTick(() => {
          setFieldsValue(Object.assign(pick(record, [
            'id',
            'no',
            'purchaseApplyId',
            'purchasePlanId',
            'demandPlanId',
            'purchaseOrderId',
            'companyId',
            'companyName',
            'projectCode',
            'projectId',
            'projectName',
            'supplierCode',
            'supplierId',
            'supplierName',
            'signDate',
            'signAddress',
            'moneyType',
            'payPeriod',
            'onePeriodName',
            'onePeriodRatio',
            'twoPeriodName',
            'twoPeriodRatio',
            'threePeriodName',
            'threePeriodRatio',
            'leadTime',
            'deliveryPlace',
            'delayTime',
            'sellerName',
            'sellerDeliveryAddress',
            'sellerUnitAddress',
            'sellerPhone',
            'sellerTaxNo',
            'sellerBankName',
            'sellerBankNo',
            'buyerName',
            'buyerDeliveryAddress',
            'buyerUnitAddress',
            'buyerPhone',
            'buyerTaxNo',
            'buyerBankName',
            'buyerBankNo',
            'quantity',
            'totalMoney',
            'content',
            'status',
            'remark',
            'delFlag'
          ])))
          this.$refs.ueditor.setContent(record.content)
        })
      })
    },
    changeSupplier (value, option) {
      // this.supplierName = option.componentOptions.propsData.label
      const supplier = this.supplierMap[value]
      const { form: { setFieldsValue } } = this
      setFieldsValue({
        supplierCode: supplier.account,
        sellerName: supplier.name,
        sellerDeliveryAddress: supplier.arriveAddress,
        sellerUnitAddress: supplier.registerAddress,
        sellerPhone: supplier.phone,
        sellerTaxNo: supplier.taxNo,
        sellerBankName: supplier.bankName,
        sellerBankNo: supplier.bankNo
      })
    },
    changePayPeriod (value) {
      this.payPeriod = value
      const { form: { setFieldsValue } } = this
      const index = value - 1
      setFieldsValue({
        onePeriodName: this.onePeriodNameDefaults[index],
        onePeriodRatio: this.onePeriodRatioDefaults[index]
      })
      if (value > 1) {
        setFieldsValue({
          twoPeriodName: this.twoPeriodNameDefaults[index],
          twoPeriodRatio: this.twoPeriodRatioDefaults[index]
        })
      }
      if (value > 2) {
        setFieldsValue({
          threePeriodName: this.threePeriodNameDefaults[index],
          threePeriodRatio: this.threePeriodRatioDefaults[index]
        })
      }
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.content = this.$refs.ueditor.getUEContent()
        // 日期处理
        values.signDate = this.BaseTool.Date.formatter(values.signDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        this.BaseTool.ListForm.setOneListValues(this, values)
        if (this.addFlag) {
          addPurchaseContract(values)
            .then(() => {
              this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
              this.BaseTool.ListForm.clearTwoList(this)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updatePurchaseContract(values)
            .then(() => {
              this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
              this.BaseTool.ListForm.clearTwoList(this)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    catchData (content) {
      this.content = content
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      this.$emit('ok', values)
    }

  }
}
</script>
