<template>
  <div>
    <BaseDialog
      width="1400px"
      :isShow.sync="isShow"
      :title="title"
      @close="close"
      @submit="submitForm"
    >
      <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="业务类型" :value="1"></el-option>
              <el-option label="非分成" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <template v-if="item.itemCategory == 1">
            <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
              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>
          </template>
          <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="{ set: 0 }"
                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="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>
          <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 } from "@/api/financed/index";
export default {
  name: "DislogSet",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    // 0 新增  1修改  2复制
    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 } = list;
      if (maxValue || value) {
        if (!value) {
          callback(new Error("请输入最低价"));
        } else if (!maxValue) {
          callback(new Error("请输入最高价"));
        } else if (maxValue <= value) {
          callback(new Error("最低价不能小于最高价"));
        }
      }
      if (businessId) {
        const levelList = this.itemList.filter(
          (e) => e.businessId == list.businessId
        );
        if (levelList.length > 1) {
          const text = this.isHaveIntersect(levelList);
          text && callback(new Error(text));
        }
      }
      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" },
        ],
        educationTypeId: [
          { required: true, message: "请选择教育类型", trigger: "change" },
        ],
        itemCategory: [
          { required: true, message: "请选择业务类型", trigger: "change" },
        ],
        itemType: [
          { required: true, message: "请选择成本类型", trigger: "change" },
        ],
        typeValue: [
          { required: true, message: "请输入百分比成本", trigger: "blur" },
        ],
        minValue: [{ validator: checkMinValue, trigger: "blur" }],
      },
      tenantList: [],
      eduList: [],
    };
  },
  methods: {
    init() {
      this.resetForm();
      this.tpId && this.getCostDetail();
      this.getTenantList();
      this.getEduList();
    },
    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 = res.rows;
      });
    },
    backbusinessList(eduId) {
      if (!eduId || !this.eduList.length) return [];
      let data = this.eduList.find((e) => e.id == eduId);
      return data.businessList || [];
    },
    getTenantList() {
      if (this.tenantList.length) return;
      this.$api.systemtenantlist().then((res) => {
        this.tenantList = res.rows;
      });
    },
    changeEdu(data) {
      data.businessId = undefined;
      data.projectId = undefined;
    },
    changeBus(data, projectId) {
      data.projectId = projectId;
    },
    add(index, data) {
      data = data
        ? JSON.parse(JSON.stringify(data))
        : {
            projectId: undefined,
            itemName: undefined,
            itemCategory: undefined,
            businessId: undefined,
            educationTypeId: undefined,
            itemType: undefined,
            typeValue: undefined,
            minValue: undefined,
            maxValue: undefined,
          };
      this.itemList.splice(index + 1, 0, data);
    },
    del(index) {
      this.itemList.splice(index, 1);
    },
    close() {
      this.$refs["form"].resetFields();
    },
    resetForm() {
      this.form = {
        itemList: [
          {
            projectId: undefined,
            itemName: undefined,
            itemCategory: undefined,
            businessId: undefined,
            educationTypeId: undefined,
            itemType: undefined,
            typeValue: undefined,
            minValue: undefined,
            maxValue: undefined,
          },
        ],
        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 !== 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() {
        if (this.dialogVisible) {
          this.init();
        }
        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>
