<template>
  <div>
    <BaseDialog
      width="1100px"
      :isShow.sync="isShow"
      :title="title"
      @close="close"
      @submit="submitForm"
      @open="init"
    >
      <div class="bop-tip">
        <div>
          <i class="el-icon-warning-outline" style="padding-right: 4px"></i>注意
        </div>
        <div>● 1、百分比成本 = 百分比*（课程金额 - 课程税前佣金）。</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="instId" label="">
            <el-select
              filterable
              v-model="form.instId"
              placeholder="请选择关联机构"
            >
              <el-option
                v-for="item in tenantList"
                :key="item.instId"
                :label="item.instName"
                :value="item.instId"
              ></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
            :label="index == 0 ? '成本设置：' : ' '"
            :prop="'itemList.' + index + '.costCatId'"
            :rules="rules['costCatId']"
            label-width="100px"
          >
            <el-select v-model="item.costCatId" placeholder="请选择成本分类">
              <el-option
                :label="item.categoryName"
                :value="item.costCatId"
                v-for="item in categoryList"
                :key="item.costCatId"
              ></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
            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,
  addInstCost,
  costInstDetail,
  editInstCost,
  instCategoryList,
} 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: "",
    },
    tenantList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    var checkBusId = (rule, value, callback) => {
      const { costCatId } = this.itemList[rule.field.split(".")[1]];
      if (this.itemList.length > 1) {
        const levelList = this.itemList.filter(
          (e) =>
            costCatId &&
            value &&
            e.businessId == value &&
            e.costCatId == costCatId
        );
        if (levelList.length > 1) {
          callback(new Error("已存在相同的成本分类！"));
        }
      }
      callback();
    };
    return {
      form: {},
      rules: {
        tpName: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
        ],
        instId: [
          { required: true, message: "请选择关联机构", trigger: "change" },
        ],
        businessId: [
          { required: true, message: "请选择业务层次", trigger: "blur" },
          { validator: checkBusId, trigger: "change" },
        ],
        educationTypeId: [
          { required: true, message: "请选择教育类型", trigger: "change" },
        ],
        costCatId: [
          { required: true, message: "请选择成本分类", trigger: "change" },
        ],
        itemType: [
          { required: true, message: "请选择成本类型", trigger: "change" },
        ],
        typeValue: [
          { required: true, message: "请输入成本值", trigger: "blur" },
        ],
      },
      eduList: [],
      categoryList: [],
    };
  },
  methods: {
    init() {
      this.resetForm();
      this.tpId && this.getcostInstDetail();
      this.getEduList();
      this.getCategoryList();
    },
    getCategoryList() {
      instCategoryList().then((res) => {
        this.categoryList = res.rows;
      });
    },
    getcostInstDetail() {
      costInstDetail(this.tpId).then((res) => {
        if (this.type == 2) delete this.form["tpId"];
        Object.keys(this.form).map((key) => {
          this.form[key] = res.data[key];
        });
      });
    },
    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 || [];
    },
    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,
        costCatId: undefined,
        businessId: undefined,
        educationTypeId: undefined,
        itemType: undefined,
        typeValue: undefined,
        dockStatus: undefined,
        dockType: undefined,
        dockValue: undefined,
      };
    },
    resetForm() {
      this.form = {
        itemList: [this.backItem()],
        tpId: undefined,
        tpName: undefined,
        defaultStatus: 0,
        instId: undefined,
      };
    },
    cb() {
      this.$message.success(this.title + "成功");
      this.isShow = false;
      this.$emit("search");
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.type !== 1) {
            addInstCost(this.form).then(this.cb);
          } else {
            editInstCost(this.form).then(this.cb);
          }
        } else {
          return false;
        }
      });
    },
  },
  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>
