<template>
  <p-form-model ref="ruleForm" class="plg-grid-from" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" :rules="rules">
    <a-divider orientation="left">基本信息</a-divider>
    <a-row>
      <a-col :span="6">
        <p-form-model-item label="合同编号" prop="contractNo">
          <div v-if="type === 'view'">{{ form.contractNo }}</div>
          <p-input v-model="form.contractNo" :disabled="type === 'edit'" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="合同名称" prop="contractName">
          <div v-if="type === 'view'">{{ form.contractName }}</div>
          <p-input v-model="form.contractName" :disabled="type === 'edit'" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="合同类型" prop="contractType">
          <div v-if="type === 'view'">{{ form.contractTypeName }}</div>
          <p-select v-model="form.contractType" :options="options.CONTRACT_TYPE" allowClear v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="结算方式" prop="settlementType">
          <div v-if="type === 'view'">{{ form.settlementTypeName }}</div>
          <p-select v-model="form.settlementType" :options="options.SETTLEMENT_WAY" allowClear v-else />
        </p-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="6">
        <p-form-model-item label="甲方" prop="firstPartyName">
          <div v-if="type === 'view'">{{ form.firstPartyTypeName }}-{{ form.firstPartyName }}</div>
          <!-- <partyA :partyA="partyA" @getPartyA="getPartyA" :disabled="type === 'edit'" v-else></partyA> -->
          <p-search-modal v-model="form.firstPartyName" v-bind="$data.$formItems.consignorAttr" @change="(...args) => onFormChange('consignor', ...args)" :disabled="type === 'edit'" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="乙方" prop="secondPartyName">
          <div v-if="type === 'view'">{{ form.secondPartyTypeName }}-{{ form.secondPartyName }}</div>
          <!-- <partyB :partyB="partyB" @getPartyB="getPartyB" :disabled="type === 'edit'" v-else></partyB> -->
          <departmenTree :departmentCode="departmentCode" @getDepartment="getDepartment" :disabled="type === 'edit'" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="对账完成日期" prop="reconciliationDate">
          <div v-if="type === 'view'">{{ form.reconciliationDate }}</div>
          <p-select v-model="form.reconciliationDate" :options="options.RECONCILIATION_DATE" allowClear v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="结算完成日期" prop="settlementDate">
          <div v-if="type === 'view'">{{ form.settlementDate }}</div>
          <p-select v-model="form.settlementDate" :options="options.RECONCILIATION_DATE" allowClear v-else />
        </p-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="6">
        <p-form-model-item label="生效日期" prop="effectiveDate">
          <div v-if="type === 'view'">{{ form.effectiveDate }}</div>
          <p-date-picker v-model="form.effectiveDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" @change="dateChange" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="失效日期" prop="expiryDate">
          <div v-if="type === 'view'">{{ form.expiryDate }}</div>
          <p-date-picker v-model="form.expiryDate" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" style="width: 100%" @change="expiryDateChange" :disabled-date="disabledEndDate" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="合同期限" prop="contractPeriod">
          <div v-if="type === 'view'">{{ form.contractPeriod }}天</div>
          <p-input v-model="form.contractPeriod" suffix="天" @change="dateChange" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="税点" prop="taxPoint">
          <div v-if="type === 'view'">{{ form.taxPoint }}</div>
          <p-select v-model="form.taxPoint" :options="options.TAX_POINT" allowClear v-else />
        </p-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="6">
        <p-form-model-item prop="isHeavyBubble">
          <p-checkbox v-model="form.isHeavyBubble" :readOnly="type === 'view'">是否启用重泡比</p-checkbox>
        </p-form-model-item>
      </a-col>
      <a-col :span="6">
        <p-form-model-item label="重泡比" prop="heavyBubble">
          <div v-if="type === 'view'">{{ form.heavyBubble }}</div>
          <p-input v-model="form.heavyBubble" suffix="吨/立方米" v-else />
        </p-form-model-item>
      </a-col>
      <a-col :span="12">
        <p-form-model-item label="备注" prop="memo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
          <div v-if="type === 'view'">{{ form.memo }}</div>
          <p-input v-model="form.memo" v-else />
        </p-form-model-item>
      </a-col>
    </a-row>
    <a-divider orientation="left" v-if="mextendedField_list.length">扩展属性</a-divider>
    <extendedField :mextendedField_list="mextendedField_list" :type="type" :form="form"></extendedField>
  </p-form-model>
</template>

<script>
import extendedField from '@/blocks/extendedField/index.vue';
import departmenTree from '@/blocks/components/formConfig/index.departmenTree.vue';
import * as $formItems from '@/blocks/components/searchModalConfig/index';

import { View } from '../js/api';
import partyA from './partyA.vue';
import partyB from './partyB.vue';

export default {
  components: { extendedField, partyA, partyB, departmenTree },
  props: {
    editId: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    mextendedField_list: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    const positveOrZero = (rule, value, callback) => {
      if (value && !/(^\d+$)/.test(value)) {
        callback(new Error('请输入正整数'));
      } else {
        callback();
      }
    };
    const heavyBubble = (rule, value, callback) => {
      if (value && !/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(value)) {
        callback(new Error('请输入非负数'));
      } else if (this.form.isHeavyBubble && !value) {
        callback(new Error('重泡比不能为空'));
      } else {
        callback();
      }
    };
    return {
      $formItems,
      form: {
        effectiveDate: '',
        expiryDate: '',
        contractPeriod: '',
        isHeavyBubble: false,
        heavyBubble: '',
        firstPartyId: '',
        firstPartyCode: '',
        firstPartyName: '',
        firstPartyType: 'C',
        secondPartyId: '',
        secondPartyCode: '',
        secondPartyName: '',
        secondPartyType: 'D',
      },
      rules: {
        contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
        contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
        contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
        settlementType: [{ required: true, message: '结算方式不能为空', trigger: 'change' }],
        firstPartyName: [{ required: true, message: '甲方不能为空', trigger: 'change' }],
        secondPartyName: [{ required: true, message: '乙方不能为空', trigger: 'change' }],
        effectiveDate: [{ required: true, message: '生效日期不能为空', trigger: 'change' }],
        expiryDate: [{ required: true, message: '失效日期不能为空', trigger: 'change' }],
        contractPeriod: [
          { required: true, message: '合同期限不能为空', trigger: 'change' },
          { validator: positveOrZero, trigger: 'change' },
        ],
        heavyBubble: [{ validator: heavyBubble, trigger: 'change' }],
        taxPoint: [{ required: true, message: '税点不能为空', trigger: 'change' }],
      },

      partyA: {
        PartyId: [],
        PartyCode: [],
        PartyName: [],
        PartyType: '',
      },
      partyB: {
        PartyId: [],
        PartyCode: [],
        PartyName: [],
        PartyType: '',
      },

      departmentCode: '',
    };
  },
  mounted() {
    if (this.editId) {
      this.spinning = true;
      View({ id: this.editId })
        .then((res) => {
          if (res.success) {
            res.data.isHeavyBubble = res.data.isHeavyBubble === 1;
            if (this.type === 'copy') {
              res.data.origContractNo = res.data.contractNo;
              res.data.contractNo = '';
              res.data.contractName = '';
            }
            this.form = { ...res.data };
            this.partyA = {
              PartyId: (this.form.firstPartyId || []).split(','),
              PartyCode: (this.form.firstPartyCode || []).split(','),
              PartyName: (this.form.firstPartyName || []).split(','),
              PartyType: this.form.firstPartyType,
            };
            this.partyB = {
              PartyId: (this.form.secondPartyId || []).split(','),
              PartyCode: (this.form.secondPartyCode || []).split(','),
              PartyName: (this.form.secondPartyName || []).split(','),
              PartyType: this.form.secondPartyType,
            };
            this.$emit('setContractInfo', this.form);
            this.departmentCode = this.form.secondPartyCode;
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    }
  },
  methods: {
    // 日期计算
    disabledStartDate(startValue) {
      const endValue = this.moment(this.expiryDate);
      if (!startValue || !endValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    disabledEndDate(endValue) {
      const startValue = this.moment(this.form.effectiveDate);
      if (!endValue || !startValue) {
        return false;
      }
      return startValue.valueOf() > endValue.valueOf();
    },
    dateChange() {
      if (this.form.effectiveDate && this.form.contractPeriod) {
        let expiryDate = this.moment(this.form.effectiveDate).add(Number(this.form.contractPeriod) - 1, 'days');
        expiryDate = this.moment(expiryDate).format('YYYY-MM-DD');
        this.$set(this.form, 'expiryDate', expiryDate);
        this.$refs.ruleForm.validateField('expiryDate');
      }
    },
    expiryDateChange() {
      if (this.form.effectiveDate && this.form.expiryDate) {
        let contractPeriod = this.moment(this.form.expiryDate).diff(this.moment(this.form.effectiveDate), 'day') + 1;
        this.$set(this.form, 'contractPeriod', contractPeriod);
        this.$refs.ruleForm.validateField('contractPeriod');
      }
    },

    getPartyA(data) {
      this.partyA = data;
      this.form.firstPartyId = data.PartyId.join(',');
      this.form.firstPartyCode = data.PartyCode.join(',');
      this.form.firstPartyName = data.PartyName.join(',');
      this.form.firstPartyType = data.PartyType;
    },
    getPartyB(data) {
      this.partyB = data;
      this.form.secondPartyId = data.PartyId.join(',');
      this.form.secondPartyCode = data.PartyCode.join(',');
      this.form.secondPartyName = data.PartyName.join(',');
      this.form.secondPartyType = data.PartyType;
    },

    onFormChange(name, ...args) {
      if (name === 'consignor') {
        this.$set(this.form, 'firstPartyId', args[1] ? args[2][0].cargoOwnerId : '');
        this.$set(this.form, 'firstPartyCode', args[1] ? args[2][0].cargoOwnerCode : '');
        this.$set(this.form, 'firstPartyName', args[1]);
      }
    },
    getDepartment(value) {
      this.departmentCode = value.departmentCode;
      this.form.secondPartyId = value.departmentId;
      this.form.secondPartyCode = value.departmentCode;
      this.form.secondPartyName = value.departmentName;
    },
  },
};
</script>