<!--
@name: 比例计费策略-编辑页
@author: 张泽贤
@time: 2022-08-02
@doc:
-->
<template>
  <p-spin class="spin-full" :spinning="spinning">
    <p-card class="full-card-panel">
      <a-space slot="title" style="display: flex; align-items: center; cursor: pointer">
        <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
        比例计费策略-{{ typeTitle }}
      </a-space>
      <p-button v-show="type !== 'view'" slot="extra" type="primary" @click="onSave">保存</p-button>

      <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="strategyName">
              <div v-if="type === 'view'">{{ form.strategyName }}</div>
              <p-input v-model="form.strategyName" :disabled="type === 'edit'" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" v-if="isRatio">
            <p-form-model-item label="比例系数" prop="ratio">
              <div v-if="type === 'view'">{{ form.ratio }}</div>
              <p-input-number v-model="form.ratio" :precision="6" placeholder="支持6位小数" v-else style="width: 100%" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" v-if="!isRatio">
            <p-form-model-item label="比例系数(分子)" prop="ratioNumerator">
              <div v-if="type === 'view'">{{ form.ratioNumerator }}</div>
              <p-input-number v-model="form.ratioNumerator" :min="1" :precision="0" v-else style="width: 100%" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" v-if="!isRatio">
            <p-form-model-item label="比例系数(分母)" prop="ratioDenominator">
              <div v-if="type === 'view'">{{ form.ratioDenominator }}</div>
              <p-input-number v-model="form.ratioDenominator" :min="1" :precision="0" v-else style="width: 100%" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" v-if="type !== 'view'">
            <p-form-model-item label="">
              <p-button type="primary" @click="onRatio">{{ isRatio ? '分数' : '小数' }}</p-button>
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <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">比例规则</a-divider>
        <a-row>
          <a-col :span="24">
            <p-form-model-item label="" prop="" :label-col="{ span: 0 }">
              <a-tag color="red">满足以下条件的单据按比例计费</a-tag>
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameBillNo">
              <p-checkbox v-model="form.isSameBillNo" :readOnly="type === 'view'">相同订单号</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameShipbillNo">
              <p-checkbox v-model="form.isSameShipbillNo" :readOnly="type === 'view'">相同运单号</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameWmsNo">
              <p-checkbox v-model="form.isSameWmsNo" :readOnly="type === 'view'">相同WMS单号</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameSender">
              <p-checkbox v-model="form.isSameSender" :readOnly="type === 'view'">相同发货方</p-checkbox>
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="4">
            <p-form-model-item label="" prop="isStartDate">
              <p-checkbox v-model="form.isStartDate" :readOnly="type === 'view'">相同实际启运日期</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameCar">
              <p-checkbox v-model="form.isSameCar" :readOnly="type === 'view'">相同运输车辆</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameDriver">
              <p-checkbox v-model="form.isSameDriver" :readOnly="type === 'view'">相同运输司机</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameCarrier">
              <p-checkbox v-model="form.isSameCarrier" :readOnly="type === 'view'">相同承运商</p-checkbox>
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameReceive">
              <p-checkbox v-model="form.isSameReceive" :readOnly="type === 'view'">相同收货方</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameEndDate">
              <p-checkbox v-model="form.isSameEndDate" :readOnly="type === 'view'">相同实际送达日期</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameElectronicBackDate">
              <p-checkbox v-model="form.isSameElectronicBackDate" :readOnly="type === 'view'">相同电子回单日期</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="4">
            <p-form-model-item label="" prop="isSameOriginalBackDate">
              <p-checkbox v-model="form.isSameOriginalBackDate" :readOnly="type === 'view'">相同正本回单日期</p-checkbox>
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">比例参照条件</a-divider>
        <p-button type="primary" @clickSync="onAddBtn" v-if="isFocus">新增</p-button>
        <a-row v-for="(item, index) in flowConditions" :key="index">
          <a-col :span="6">
            <p-form-model-item label="" prop="flowConditionType" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-select v-model="item.flowConditionType" :options="BMS_APPROVAL_CONDITION_TYPE" allowClear @change="(value) => flowConditionTypeChange(value, item)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.flowConditionType !== 8 && item.flowConditionType !== 9 && item.flowConditionType !== 10 && item.flowConditionType !== 11">
            <p-form-model-item label="" prop="flowConditionValue" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-select v-model="item.flowConditionValue" :options="flowConditionValueEnums[item.flowConditionType]" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="(item.flowConditionType === 2 || item.flowConditionType === 3) && item.flowConditionValue === 1">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="customerAttr" @change="(...args) => onFormChange('customer', item, ...args)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="(item.flowConditionType === 2 || item.flowConditionType === 3) && item.flowConditionValue === 2">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="branchAttr" @change="(...args) => onFormChange('branch', item, ...args)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="(item.flowConditionType === 2 || item.flowConditionType === 3) && item.flowConditionValue === 3">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="supplierAttr" @change="(...args) => onFormChange('supplier', item, ...args)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.flowConditionType === 8">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="$data.$formItems.consignorAttr" @change="(...args) => onFormChange('consignor', item, ...args)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.flowConditionType === 9">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <departmenTree :departmentCode="departmentCode" @getDepartment="(value) => getDepartment(value, item)" :disabled="!isFocus"></departmenTree>
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.flowConditionType === 10">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="itemAttr" @change="(...args) => onFormChange('item', item, ...args)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="6" style="margin-left: 10px" v-show="item.flowConditionType === 11">
            <p-form-model-item label="" prop="unitName" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <p-search-modal v-model="item.unitName" v-bind="categoryAttr" @change="(...args) => onFormChange('category', item, ...args)" :disabled="!isFocus" />
            </p-form-model-item>
          </a-col>
          <a-col :span="2">
            <p-form-model-item style="text-align: right">
              <a-space>
                <p-button type="danger" @click="onDelBtn(index)" v-if="isFocus">删除</p-button>
              </a-space>
            </p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>
    </p-card>
  </p-spin>
</template>

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

import { View, Save, Update } from '../js/api';

export default {
  components: { departmenTree },
  props: {
    type: {
      type: String,
      default: '',
    },
    editId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
        copy: '复制',
      };
      return dictionary[this.type] || this.type;
    },
    isFocus() {
      return this.type === 'add' || this.type === 'edit';
    },
    customerAttr() {
      let customerAttr = $formItems.customerAttr;
      customerAttr.tableConfig.rowSelectType = 2;
      return customerAttr;
    },
    branchAttr() {
      let branchAttr = $formItems.branchAttr;
      branchAttr.tableConfig.rowSelectType = 2;
      return branchAttr;
    },
    supplierAttr() {
      let supplierAttr = $formItems.supplierNoConsignorAttr;
      supplierAttr.tableConfig.rowSelectType = 2;
      return supplierAttr;
    },
    itemAttr() {
      let itemAttr = $formItems.itemAttr;
      itemAttr.tableConfig.rowSelectType = 2;
      return itemAttr;
    },
    categoryAttr() {
      let categoryAttr = $formItems.categoryAttr;
      categoryAttr.tableConfig.rowSelectType = 2;
      return categoryAttr;
    },
  },
  data() {
    return {
      spinning: false,
      $formItems,

      form: {
        isSameBillNo: false,
        isSameShipbillNo: false,
        isSameWmsNo: false,
        isSameSender: false,
        isStartDate: false,
        isSameCar: false,
        isSameDriver: false,
        isSameCarrier: false,
        isSameReceive: false,
        isSameEndDate: false,
        isSameElectronicBackDate: false,
        isSameOriginalBackDate: false,
        ratio: '',
        ratioNumerator: '',
        ratioDenominator: '',
      },
      rules: {
        strategyName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
        ratio: [{ required: true, message: '比例系数不能为空', trigger: 'blur' }],
        ratioNumerator: [{ required: true, message: '比例系数(分子)不能为空', trigger: 'blur' }],
        ratioDenominator: [{ required: true, message: '比例系数(分母)不能为空', trigger: 'blur' }],
      },

      flowConditions: [],
      flowConditionValueEnums: {
        1: this.options.DELIVERY_METHOD_TYPE, // 配送方式
        2: this.options.SHIPPER_TYPE, // 发货商类型
        3: this.options.CONSIGNEE_TYPE, // 收货方类型
        4: this.options.ORDER_TYPE, // 订单类型
        5: this.options.ORDER_BUSINESS_TYPE, // 订单业务类型
        6: this.options.TRANSPORT_TYPE, // 运输类型
        7: this.options.TEMPERATURE_REQUIREMENT, // 温度要求
        8: [], // 货主
        9: [], // 部门
      },
      BMS_APPROVAL_CONDITION_TYPE: [],

      departmentCode: '', // 部门code

      isRatio: true,
    };
  },
  mounted() {
    this.BMS_APPROVAL_CONDITION_TYPE = this.options.BMS_APPROVAL_CONDITION_TYPE.map((item) => {
      item.disabled = false;
      return item;
    });

    if (this.editId) {
      this.spinning = true;
      View({ id: this.editId })
        .then((res) => {
          if (res.success) {
            this.isRatio = !!res.data.ratio;

            res.data.isSameBillNo = res.data.isSameBillNo == 1;
            res.data.isSameShipbillNo = res.data.isSameShipbillNo == 1;
            res.data.isSameWmsNo = res.data.isSameWmsNo == 1;
            res.data.isSameSender = res.data.isSameSender == 1;
            res.data.isStartDate = res.data.isStartDate == 1;
            res.data.isSameCar = res.data.isSameCar == 1;
            res.data.isSameDriver = res.data.isSameDriver == 1;
            res.data.isSameCarrier = res.data.isSameCarrier == 1;
            res.data.isSameReceive = res.data.isSameReceive == 1;
            res.data.isSameEndDate = res.data.isSameEndDate == 1;
            res.data.isSameElectronicBackDate = res.data.isSameElectronicBackDate == 1;
            res.data.isSameOriginalBackDate = res.data.isSameOriginalBackDate == 1;
            this.form = { ...res.data };
            delete this.form.flowConditions;
            this.flowConditions = [...res.data.flowConditions];
            this.FLOW_CONDITION_TYPE_INIT();

            // 处理部门渲染
            this.$nextTick(() => {
              this.flowConditions.forEach((item) => {
                if (item.flowConditionType === 9) {
                  this.departmentCode = item.unitCode;
                }
              });
            });
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    }
  },
  methods: {
    back() {
      this.$emit('back');
    },

    // 保存
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        if (this.type === 'add' || this.type === 'copy') this.onMethod(Save);
        if (this.type === 'edit') this.onMethod(Update);

        return;
      });
    },
    onMethod(method) {
      let params = { ...this.form };
      params.isSameBillNo = params.isSameBillNo ? 1 : 0;
      params.isSameShipbillNo = params.isSameShipbillNo ? 1 : 0;
      params.isSameWmsNo = params.isSameWmsNo ? 1 : 0;
      params.isSameSender = params.isSameSender ? 1 : 0;
      params.isStartDate = params.isStartDate ? 1 : 0;
      params.isSameCar = params.isSameCar ? 1 : 0;
      params.isSameDriver = params.isSameDriver ? 1 : 0;
      params.isSameCarrier = params.isSameCarrier ? 1 : 0;
      params.isSameReceive = params.isSameReceive ? 1 : 0;
      params.isSameEndDate = params.isSameEndDate ? 1 : 0;
      params.isSameElectronicBackDate = params.isSameElectronicBackDate ? 1 : 0;
      params.isSameOriginalBackDate = params.isSameOriginalBackDate ? 1 : 0;

      params.flowConditions = [...this.flowConditions];

      if (params.ratioNumerator > params.ratioDenominator) {
        this.$message.error('比例系数分子不能大于分母');
        return false;
      }

      this.spinning = true;
      method(params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$emit('back');
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    onFormChange(name, item, ...args) {
      if (!args[1]) {
        this.$set(item, 'unitId', '');
        this.$set(item, 'unitCode', '');
        this.$set(item, 'unitName', '');
        return;
      }
      if (name === 'consignor') {
        this.$set(item, 'unitId', args[2][0].cargoOwnerId);
        this.$set(item, 'unitCode', args[2][0].cargoOwnerCode);
        this.$set(item, 'unitName', args[2][0].cargoOwnerName);
      } else {
        let id = 'id',
          code = 'code';
        if (name === 'item') {
          id = 'itemId';
          code = 'itemCode';
        } else if (name === 'category') {
          id = 'itemCategoryId';
          code = 'itemCategoryCode';
        }
        let idList = [],
          codeList = [];
        args[2].forEach((item) => {
          idList.push(item[id]);
          codeList.push(item[code]);
        });
        this.$set(item, 'unitId', idList.join(','));
        this.$set(item, 'unitCode', codeList.join(','));
        this.$set(item, 'unitName', args[1]);
      }
    },
    onAddBtn() {
      this.flowConditions.push({
        flowConditionType: '',
        flowConditionValue: '',
        flowConditionValueEnums: [],
        unitId: '',
        unitCode: '',
        unitName: '',
      });
    },
    onDelBtn(index) {
      this.flowConditions.splice(index, 1);
      this.FLOW_CONDITION_TYPE_INIT();
    },
    flowConditionTypeChange(value, item) {
      item.flowConditionValue = '';
      item.unitId = '';
      item.unitCode = '';
      item.unitName = '';
      this.FLOW_CONDITION_TYPE_INIT();
    },
    // 更新FLOW_CONDITION_TYPE
    FLOW_CONDITION_TYPE_INIT() {
      let selectList = this.flowConditions.map((item) => item.flowConditionType);
      this.BMS_APPROVAL_CONDITION_TYPE.forEach((item) => {
        if (selectList.includes(item.value)) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      });
    },
    // 部门change
    getDepartment(value, item) {
      this.departmentCode = value.departmentCode;
      item.unitId = value.departmentId;
      item.unitCode = value.departmentCode;
      item.unitName = value.departmentName;
    },

    onRatio() {
      this.isRatio = !this.isRatio;
      this.form.ratio = '';
      this.form.ratioNumerator = '';
      this.form.ratioDenominator = '';
    },
  },
};
</script>

<style lang="less" scoped>
.border {
  border: 1px solid #e8e8e8;
}
</style>