<template>
  <p-spin :spinning="spinning">
    <p-card>
      <div slot="title" style="display: inline-block; cursor: pointer" @click="back">
        <a-icon class="mr-10" style="color: #1990ff" type="arrow-left" />
        订单排序规则
      </div>
      <div v-if="type !== 'view'" slot="extra">
        <p-button type="primary" @click="onSubmit">保存</p-button>
      </div>
      <p-form-model
        ref="formTarget"
        :label-col="{ span: 8 }"
        :model="form"
        :wrapper-col="{ span: 16 }"
        class="plg-grid-from"
      >
        <a-row v-for="(item, index) in form.formList" :key="item.billSortRuleId">
          <a-col :span="6">
            <p-form-model-item label="单据类型">
              <p-select
                v-model="item.billType"
                :options="billTypeOptions"
                :disabled="type === 'view'"
                allowClear
                @change="(value, label) => billTypeChange(value, label, index)"
              />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item
              label="配送方式"
              :prop="'formList.' + index + '.deliverType'"
              :rules="{ required: true, message: '请选择配送方式', trigger: 'change' }"
            >
              <p-select
                v-model="item.deliverType"
                :options="deliverTypeOptions"
                :disabled="type === 'view'"
                allowClear
                @change="(value, label) => distributionMethodChange(value, label, index)"
              />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item
              label="顺序号"
              :prop="'formList.' + index + '.priority'"
              :rules="{ required: true, message: '请输入顺序号', trigger: 'change' }"
            >
              <p-input v-model="item.priority" :disabled="type === 'view'" allowClear />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item
              label="紧急程度"
              :prop="'formList.' + index + '.priorityLevel'"
              :rules="{ required: true, message: '请输入紧急程度', trigger: 'change' }"
            >
              <p-select
                v-model="item.priorityLevel"
                :options="deliverTypeOptions1"
                @change="(value, label) => billTypeChange1(value, label, index)"
                :disabled="type === 'view'"
                allowClear
              />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item :wrapper-col="{ span: 20, offset: 4 }">
              <p-button v-if="index === 0" type="primary" @click="addRow">添加</p-button>
              <p-button v-if="index > 0" @click="delRow(item)">删除</p-button>
            </p-form-model-item>
          </a-col>
        </a-row>
      </p-form-model>
    </p-card>
  </p-spin>
</template>

<script>
import { getDictionary, saveRule, update } from "./api";

export default {
  props: {
    type: "",
    editData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      spinning: false,
      form: {
        formList: [],
      },
      delDataSource: [],
      // 字典
      billTypeOptions: [],
      deliverTypeOptions: [],
      deliverTypeOptions1: [],
    };
  },
  mounted() {
    this.initDictionary();
    // 出库单类型 	do_bill_type
    // 提货方式   pub_workstage_delivertype
    if (this.type === "add") {
      this.addRow();
    }
    if (this.type === "edit" && Array.isArray(this.editData)) {
      this.form.formList.push(...this.editData);
    }
  },
  computed: {
    warehouse() {
      return this.$store.getters.warehouse || {};
    },
  },
  methods: {
    initDictionary() {
      getDictionary("bill_type_value").then((options) => {
        this.billTypeOptions = options;
      });
      
      getDictionary("pub_workstage_delivertype").then((options) => {
        this.deliverTypeOptions = options;
      });
      getDictionary("ASN_PRIORITY_LEVEL").then((options) => {
        this.deliverTypeOptions1 = options;
      });
    },
    back() {
      this.$emit("back");
    },
    addRow() {
      const billSortRuleId = Math.floor(Math.random() * 1000000);
      this.form.formList.push({ billSortRuleId, billType: "", deliverType: "", priority: "" });
    },
    delRow(record) {
      const { billSortRuleId } = record;
      const index = this.form.formList.findIndex((_) => _.billSortRuleId === billSortRuleId);
      if (index === -1) return;
      const delRecordArr = this.form.formList.splice(index, 1);
      this.delDataSource.push(...delRecordArr);
    },
    // 保存提交
    onSubmit() {
      this.$refs.formTarget.validate((flag) => {
        if (!flag) return;
        this.saveRule();
      });
    },
    saveRule() {
      const formList = this.form.formList;
      // const deleteItems = this.delDataSource
      const warehouse = this.warehouse;
      const saveFn = this.type === "add" ? saveRule : update;
      const saveItems = formList.map((item) => {
        const tempItem = { ...item };
        // if (item.billSortRuleId?.includes("local")) delete item.billSortRuleId;
        return { ...tempItem, ...warehouse, isEnabled: "1" };
      });
      //   saveItems
      //     private List<BillSortRuleVO> insertItems;
      // private List<BillSortRuleVO> updateItems;
      // private List<BillSortRuleVO> deleteItems;
      let data = {};
      if (this.type == "add") {
        data.insertItems = saveItems;
      } else {
        data.updateItems = saveItems;
      }
      console.log(data);
      saveFn(data)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.back();
          } else {
            this.$message.warn(res.message);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    billTypeChange(value, label, index) {
      this.form.formList[index].billTypeName = label;
    },
    billTypeChange1(value, label, index) {
      this.form.formList[index].priorityLevel = label;
    },
    distributionMethodChange(value, label, index) {
      this.form.formList[index].distributionMethodName = label;
    },
  },
};
</script>

<style lang="less" scoped>
::v-deep .ant-select,
::v-deep .ant-input-number {
  width: 100%;
}
</style>
