<template>
  <div>
    <BaseDialog
      width="1800px"
      :isShow.sync="isShow"
      :title="title"
      @close="close"
      @submit="submitForm"
      @open="init"
    >
      <div class="bop-tip">
        <div><i class="el-icon-warning-outline"></i>说明</div>
        <div>
          ●
          如果提成方式是按阶梯价计算，则需设置阶梯价格区间（最高价无穷大，则填写
          “ * ” ）。如果无需按阶梯价计算提成，留空即可。
        </div>
      </div>
      <el-form
        inline
        hide-required-asterisk
        :model="form"
        :rules="rules"
        ref="form"
      >
        <div>
          <el-form-item prop="tpName" label="模板名称：" label-width="100px">
            <el-input
              placeholder="请输入模板名称"
              v-model="form.tpName"
            ></el-input>
          </el-form-item>
          <el-form-item prop="tenantId" label="">
            <el-select
              filterable
              v-model="form.tenantId"
              placeholder="请选择关联机构"
            >
              <el-option
                v-for="item in tenantList"
                :key="item.tenantId"
                :label="item.tenantName"
                :value="item.tenantId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-checkbox
              :true-label="1"
              :false-label="0"
              v-model="form.defaultStatus"
              >默认</el-checkbox
            >
          </el-form-item>
        </div>

        <div v-for="(item, index) in form.itemList" :key="index">
          <el-form-item
            :prop="'itemList.' + index + '.itemName'"
            :label="index == 0 ? '成本设置：' : ' '"
            :rules="rules['itemName']"
            label-width="100px"
          >
            <el-input
              placeholder="请输入成本项名称"
              v-model="item.itemName"
            ></el-input>
          </el-form-item>
          <el-form-item
            label=""
            :prop="'itemList.' + index + '.itemCategory'"
            :rules="rules['itemCategory']"
          >
            <el-select v-model="item.itemCategory" placeholder="请选择成本类别">
              <el-option
                :label="item.categoryName"
                :value="item.categoryId"
                v-for="item in categoryList"
                :key="item.categoryId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label=""
            :prop="'itemList.' + index + '.educationTypeId'"
            :rules="rules['educationTypeId']"
          >
            <el-select
              @change="changeEdu(item)"
              v-model="item.educationTypeId"
              placeholder="请选择教育类型"
            >
              <el-option
                v-for="item in eduList"
                :key="item.id"
                :label="
                  item.schemeName +
                  (item.schemeName ? '-' : '') +
                  item.educationName
                "
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="item.educationTypeId != -1"
            label=""
            :prop="'itemList.' + index + '.businessId'"
            :rules="rules['businessId']"
          >
            <el-select
              filterable
              v-model="item.businessId"
              placeholder="请选择业务层次"
            >
              <el-option
                v-for="level in backbusinessList(item.educationTypeId)"
                :key="level.businessId"
                :label="level.aliasName"
                :value="level.businessId"
                @click.native="changeBus(item, level.projectId)"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label=""
            :prop="'itemList.' + index + '.itemType'"
            :rules="rules['itemType']"
          >
            <el-select v-model="item.itemType" placeholder="请选择成本类型">
              <el-option label="百分比" :value="1"></el-option>
              <el-option label="固定" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label=""
            :prop="'itemList.' + index + '.minValue'"
            :rules="rules['minValue']"
            class="range"
          >
            <el-col :span="11">
              <el-input
                v-int
                placeholder="最低价"
                v-model.number="item.minValue"
              ></el-input>
            </el-col>
            <el-col class="line" :span="2" style="magrin: 10px">-</el-col>
            <el-col :span="11">
              <el-input
                @keyup.native="regValue(item)"
                placeholder="最高价"
                @change="changeMaxValue('itemList.' + index + '.minValue')"
                v-model.number="item.maxValue"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="item.itemType"
            class="ddd"
            label-width="0"
            :prop="'itemList.' + index + '.typeValue'"
            label=" "
            :rules="rules['typeValue']"
          >
            <el-input
              v-if="item.itemType == 1"
              placeholder="输入百分比"
              v-model="item.typeValue"
              key="2"
              v-int="{ max: 100 }"
            >
              <template slot="append"> % </template>
            </el-input>
            <el-input
              key="1"
              v-else
              placeholder="固定金额"
              v-model="item.typeValue"
              v-int
            >
              <template slot="append"> 元 </template>
            </el-input>
          </el-form-item>
          <template v-if="item.itemCategory == 1">
            <el-form-item label="">
              <el-checkbox
                :true-label="1"
                :false-label="0"
                v-model="item.dockStatus"
                >成本扣除</el-checkbox
              >
            </el-form-item>
            <template v-if="item.dockStatus == 1">
              <el-form-item
                label=""
                :prop="'itemList.' + index + '.dockType'"
                :rules="rules['dockType']"
              >
                <el-select v-model="item.dockType" placeholder="请选择扣除类型">
                  <el-option label="百分比扣除" :value="1"></el-option>
                  <el-option label="固定扣除" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                v-if="item.dockType"
                class="ddd"
                label-width="0"
                :prop="'itemList.' + index + '.dockValue'"
                label=" "
                :rules="rules['dockValue']"
              >
                <el-input
                  v-if="item.dockType == 1"
                  placeholder="输入百分比"
                  v-model="item.dockValue"
                  key="2"
                  v-int="{ max: 100 }"
                >
                  <template slot="append"> % </template>
                </el-input>
                <el-input
                  key="1"
                  v-else
                  placeholder="固定金额"
                  v-model="item.dockValue"
                  v-int
                >
                  <template slot="append"> 元 </template>
                </el-input>
              </el-form-item>
            </template>
          </template>
          <el-form-item label-width="0" label=" ">
            <div class="btns">
              <i @click="add(index, item)" class="el-icon-connection"></i>
              <i @click="add(index)" class="el-icon-circle-plus-outline"></i>
              <i
                v-if="index != 0"
                @click="del(index)"
                class="el-icon-remove-outline"
              ></i>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </BaseDialog>
  </div>
</template>

<script>
import {
  eduList,
  addCost,
  costDetail,
  editCost,
  categoryList,
} from "@/api/financed/index";
export default {
  name: "DislogSet",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    // 0 新增  1修改  2复制  3订单成本设置  4批量设置
    type: {
      type: [String, Number],
      default: 0,
    },
    tpId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    var checkMinValue = (rule, value, callback) => {
      const list = this.itemList[rule.field.split(".")[1]];
      const { maxValue, businessId, itemCategory } = list;
      if (maxValue || value || value === 0) {
        if (!value && value !== 0) {
          callback(new Error("请输入最低价"));
        } else if (!maxValue) {
          callback(new Error("请输入最高价"));
        } else if (maxValue <= value) {
          callback(new Error("最低价不能小于最高价"));
        }
      }

      if (businessId && itemCategory) {
        const levelList = this.itemList.filter(
          (e) =>
            e.businessId == list.businessId && e.itemCategory == itemCategory
        );
        if (levelList.length > 1) {
          const text = this.isHaveIntersect(levelList);
          text && callback(new Error(text));
        }
      }
      callback();
    };
    var checkEduId = (rule, value, callback) => {
      const { itemCategory } = this.itemList[rule.field.split(".")[1]];
      if (this.itemList.length > 1) {
        const levelList = this.itemList.filter(
          (e) => e.itemCategory && e.itemCategory == itemCategory
        );
        const len = levelList.length;
        if (len > 1) {
          const len1 = levelList.filter((e) => e.educationTypeId == -1).length;
          if (len1 > 0 && len1 != len) {
            callback(new Error("需统一不限！"));
          }
        }
      }
      callback();
    };
    var checkBusId = (rule, value, callback) => {
      const { educationTypeId, itemCategory } =
        this.itemList[rule.field.split(".")[1]];
      if (this.itemList.length > 1) {
        const levelList = this.itemList.filter(
          (e) =>
            itemCategory &&
            educationTypeId &&
            e.educationTypeId == educationTypeId &&
            e.itemCategory == itemCategory
        );
        const len = levelList.length;
        if (len > 1) {
          const len1 = levelList.filter((e) => e.businessId == -1).length;
          if (len1 > 0 && len1 != len) {
            callback(new Error("需统一不限！"));
          }
        }
      }
      callback();
    };
    return {
      form: {},
      rules: {
        tpName: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
        ],
        tenantId: [
          { required: true, message: "请选择关联机构", trigger: "change" },
        ],
        itemName: [
          { required: true, message: "请输入成本项名称", trigger: "blur" },
        ],
        businessId: [
          { required: true, message: "请选择业务层次", trigger: "blur" },
          { validator: checkBusId, trigger: "change" },
        ],
        educationTypeId: [
          { required: true, message: "请选择教育类型", trigger: "change" },
          { validator: checkEduId, trigger: "change" },
        ],
        itemCategory: [
          { required: true, message: "请选择业务类型", trigger: "change" },
        ],
        itemType: [
          { required: true, message: "请选择成本类型", trigger: "change" },
        ],
        typeValue: [
          { required: true, message: "请输入成本值", trigger: "blur" },
        ],
        dockType: [
          { required: true, message: "请选择扣除类型", trigger: "change" },
        ],
        dockValue: [
          { required: true, message: "请输入扣除值", trigger: "blur" },
        ],
        minValue: [{ validator: checkMinValue, trigger: "blur" }],
      },
      tenantList: [],
      eduList: [],
      categoryList: [],
    };
  },
  methods: {
    init() {
      this.resetForm();
      if (this.type === 3) {
        this.getOrderCostDetail();
      } else if (this.type === 4) {
      } else {
        this.tpId && this.getCostDetail();
      }
      this.getCategoryList();
      this.getTenantList();
      this.getEduList();
    },
    getCategoryList() {
      categoryList({ status: "0,1" }).then((res) => {
        this.categoryList = res.rows;
      });
    },
    getOrderCostDetail() {
      this.$api.systemtopordercost(this.tpId).then((res) => {
        Object.keys(this.form).map((key) => {
          this.form[key] = res.data[key];
        });
        this.form.itemList.forEach((ele) => {
          if (ele.maxValue == -1) {
            ele.maxValue = "*";
          }
        });
      });
    },
    getCostDetail() {
      costDetail(this.tpId).then((res) => {
        if (this.type == 2) delete this.form["tpId"];
        Object.keys(this.form).map((key) => {
          this.form[key] = res.data[key];
        });
        this.form.itemList.forEach((ele) => {
          if (ele.maxValue == -1) {
            ele.maxValue = "*";
          }
        });
      });
    },
    getEduList() {
      if (this.eduList.length) return;
      eduList({}).then((res) => {
        this.eduList = [
          { schemeName: "", educationName: "不限", id: -1 },
          ...res.rows,
        ];
      });
    },
    backbusinessList(eduId) {
      if (!eduId || !this.eduList.length) return [];
      let data = this.eduList.find((e) => e.id == eduId);
      return data.businessList
        ? [
            { aliasName: "不限", businessId: -1, projectId: -1 },
            ...data.businessList,
          ]
        : [];
    },
    getTenantList() {
      if (this.tenantList.length) return;
      this.$api.systemtenantlist().then((res) => {
        this.tenantList = res.rows;
      });
    },
    changeEdu(data) {
      let value = data.educationTypeId == -1 ? -1 : undefined;
      data.businessId = value;
      data.projectId = value;
    },
    changeBus(data, projectId) {
      data.projectId = projectId;
    },
    add(index, data) {
      data = data ? JSON.parse(JSON.stringify(data)) : this.backItem();
      this.itemList.splice(index + 1, 0, data);
    },
    del(index) {
      this.itemList.splice(index, 1);
    },
    close() {
      this.$nextTick(() => {
        this.$refs["form"].resetFields();
      });
    },
    backItem() {
      return {
        projectId: undefined,
        itemName: undefined,
        itemCategory: undefined,
        businessId: undefined,
        educationTypeId: undefined,
        itemType: undefined,
        typeValue: undefined,
        minValue: undefined,
        maxValue: undefined,
        dockStatus: undefined,
        dockType: undefined,
        dockValue: undefined,
      };
    },
    resetForm() {
      this.form = {
        itemList: [this.backItem()],
        tpId: undefined,
        tpName: undefined,
        defaultStatus: 0,
        tenantId: undefined,
      };
    },
    cb() {
      this.$message.success(this.title + "成功");
      this.isShow = false;
      this.$emit("search");
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form));
          form.itemList.forEach((ele) => {
            if (ele.maxValue === "*") {
              ele.maxValue = -1;
            }
          });
          if (this.type === 3 || this.type === 4) {
            this.$api
              .systemtoporderupdatecost({
                costTpVo: form,
                orderSnList:
                  this.type === 3 ? [this.tpId] : this.tpId?.split(","),
              })
              .then(this.cb);
          } else if (this.type !== 1) {
            addCost(form).then(this.cb);
          } else {
            editCost(form).then(this.cb);
          }
        } else {
          return false;
        }
      });
    },
    changeMaxValue(prop) {
      this.$refs.form.validateField(prop);
    },
    // 阶梯校验
    isHaveIntersect(list) {
      const isEmpty = list.some((e) => !e.minValue && !e.maxValue);
      if (isEmpty) {
        return "非阶梯计价只能存在一个";
      }
      let maxList = list.filter((e) => e.maxValue === "*");
      if (maxList.length > 1) {
        return "阶梯计价存在范围冲突";
      }
      list.sort((a, b) => {
        if (a.maxValue == "*") {
          return Number.MAX_VALUE;
        }
        if (b.maxValue == "*") {
          return -Number.MAX_VALUE;
        }
        return a.minValue - b.minValue;
      });
      for (let i = 0, len = list.length - 1; i < len; i++) {
        if (list[i].maxValue >= list[i + 1].minValue) {
          return "阶梯计价存在范围冲突";
        }
      }
      return;
    },
    regValue(data) {
      let { maxValue } = data;
      let val;
      if (maxValue.includes("*")) {
        val = "*";
      } else {
        val = maxValue.replace(/[^0-9]/g, "");
      }
      data.maxValue = val;
    },
  },
  computed: {
    isShow: {
      get() {
        return this.dialogVisible;
      },
      set(val) {
        this.$emit("update:dialogVisible", false);
      },
    },
    title() {
      return ["新增", "修改", "复制", "订单成本设置", "批量成本设置"][
        this.type
      ];
    },
    itemList() {
      return this.form.itemList;
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-input--medium .el-input__inner {
  width: 144px;
}
/deep/ .range {
  .el-form-item__content {
    width: 170px;
  }
  .el-input--medium .el-input__inner {
    width: 76px;
  }
}
/deep/ .ddd {
  margin-left: -10px;
  .el-input--medium .el-input__inner {
    width: 105px;
  }
}
.line {
  text-align: center;
}
.btns {
  height: 36px;
  display: flex;
  align-items: center;
  i {
    font-size: 24px;
    cursor: pointer;
    margin-left: 5px;
  }
}
.bop-tip {
  background: #fff6f7;
  margin: 0 0 20px 10px;
  padding: 8px 10px;
  i {
    font-size: 16px;
    color: #e6a23c;
  }
}
</style>
