<template>
  <div class="m-container">
    <h2>课酬预警设置</h2>
    <div class="m-core">
      <!-- 搜索标题 -->
      <save-form
        :inline="true"
        ref="searchForm"
        class="searchForm"
        :model.sync="searchForm"
      >
        <el-form-item prop="organId">
          <el-select
            v-model.trim="searchForm.organId"
            placeholder="请选择分部"
            clearable
            filterable
            size="mini"
          >
            <el-option
              v-for="item in selects.branchs"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="danger" size="mini">搜索</el-button>
        </el-form-item>
      </save-form>
      <auth auths="sysConfig/update/insert" style="margin-bottom: 20px">
        <el-button
          size="mini"
          icon="el-icon-plus"
          type="primary"
          @click="openTypes('create')"
          >添加</el-button
        >
      </auth>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table
          :data="tableList"
          size="mini"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column align="center" prop="branchName" label="分部">
          </el-table-column>
          <el-table-column align="center" prop="money" label="预警课酬">
            <template slot-scope="scope">
              {{ scope.row.money | moneyFormat }}元
            </template>
          </el-table-column>
          <!-- <el-table-column align='center'
                           prop="name"
                           label="修改日期">
          </el-table-column> -->
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <auth auths="sysConfig/update/update">
                <el-button @click="openTypes('update', scope.row)" type="text"
                  >修改</el-button
                >
              </auth>
              <auth auths="sysConfig/update/del">
                <el-button @click="onTypesDel(scope.row)" type="text"
                  >删除</el-button
                >
              </auth>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog
      :title="formTitle[formActionTitle]"
      :visible.sync="typeStatus"
      @close="onFormClose('ruleForm')"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item
          label="预警课酬(元)"
          prop="money"
          :label-width="formLabelWidth"
        >
          <!-- <el-input-number v-model="form.money" controls-position="right" style="width: 100%;" :precision='2' :min="1" :max="10"></el-input-number> -->
          <el-input
            v-model.trim="form.money"
            type="number"
            @input="checkNumber(form.money)"
            placeholder="请输入预警课酬"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="适用分部"
          prop="branchId"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.branchId"
            clearable
            filterable
            placeholder="请选择适用分部"
          >
            <el-option
              v-for="item in selects.branchs"
              :value="item.id"
              :label="item.name"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="typeStatus = false">取 消</el-button>
        <el-button type="primary" @click="onTypesSubmit('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { sysConfigUpdate, queryByParamName } from "@/api/generalSettings";
export default {
  name: "earlyWarning",
  data() {
    return {
      searchForm: {
        organId: null,
      },
      tableList: [],
      tempTableList: [],
      formActionTitle: "create",
      formTitle: {
        create: "添加预警课酬设置",
        update: "修改预警课酬设置",
      },
      typeStatus: false,
      formLabelWidth: "120px",
      form: {
        id: null,
        money: null,
        branchId: null,
      },
      formRow: null,
      rules: {
        money: [{ required: true, message: "请输入预警课酬", trigger: "blur" }],
        branchId: [
          { required: true, message: "请选择适用分部", trigger: "blur" },
        ],
      },
    };
  },
  async mounted() {
    await this.$store.dispatch("setBranchs");

    this.getList();
  },
  methods: {
    //方法一：
    checkNumber(withdrawAmount) {
      this.form.money = withdrawAmount.match(/^\d*(\.?\d{0,2})/g)[0] || null;
    },
    onTypesSubmit(formName) {
      // 添加数据
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const form = this.form;
          let status = false;
          let statusName = null;
          let object = {};
          this.tempTableList.forEach((branch) => {
            if (this.formActionTitle == "update") {
              if (
                branch.branchId == form.branchId &&
                this.formRow.branchId != form.branchId
              ) {
                status = true;
                statusName = branch.branchName;
              }
            } else {
              if (branch.branchId == form.branchId) {
                status = true;
                statusName = branch.branchName;
              }
            }
            object[branch.branchId] = branch.money;
          });
          if (status) {
            this.$message.error(`[${statusName}]分部已设置预警课酬`);
            return;
          }
          object[form.branchId] = form.money;
          let params = {
            id: form.id,
            paranValue: JSON.stringify(object),
            paramName: "warning_min_course_salary",
          };
          await sysConfigUpdate(params).then((res) => {
            let title = this.formActionTitle == "create" ? "添加" : "修改";
            this.messageTips(title, res);
          });
        } else {
          return false;
        }
      });
    },
    search() {
      // this.getList()
      let organId = this.searchForm.organId;
      let tempList = [];
      this.tempTableList.forEach((item) => {
        if (item.branchId == organId || !organId) {
          tempList.push(item);
        }
      });
      this.tableList = tempList;
    },
    async onTypesDel(row) {
      let object = {};
      this.tempTableList.forEach((item) => {
        if (row.branchId != item.branchId) {
          object[item.branchId] = item.money;
        }
      });
      let params = {
        id: this.form.id,
        paranValue: JSON.stringify(object),
        paramName: "warning_min_course_salary",
      };
      this.$confirm("是否删除预警课酬", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await sysConfigUpdate(params).then((res) => {
            this.messageTips("删除", res);
          });
        })
        .catch(() => {});
    },
    async messageTips(title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.typeStatus = false;
        await this.getList();
        await this.search();
      } else {
        this.$message.error(res.msg);
      }
    },
    async getList() {
      await queryByParamName({
        paramName: "warning_min_course_salary",
      }).then((res) => {
        let result = res.data;
        if (res.code == 200) {
          const paranValue = result.paranValue
            ? JSON.parse(result.paranValue)
            : {};
          this.form.id = result.id;
          const branchs = this.selects.branchs;
          const tempValue = [];
          for (let i in paranValue) {
            let branchName = [];
            branchs.forEach((branch) => {
              if (i == branch.id) {
                branchName = branch.name;
                tempValue.push({
                  branchId: i,
                  branchName: branchName,
                  money: paranValue[i],
                });
              }
            });
          }
          this.tableList = tempValue;
          this.tempTableList = tempValue;
        }
      });
    },
    openTypes(type, row) {
      this.typeStatus = true;
      this.formActionTitle = type;
      // 修改的时候赋值
      if (type == "update") {
        this.formRow = row;
        this.$nextTick(() => {
          (this.form.money = row.money),
            (this.form.branchId = parseInt(row.branchId));
        });
      }
    },
    onFormClose(formName) {
      // 关闭弹窗重置验证
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
/deep/.el-date-editor.el-input {
  width: 100% !important;
}
/deep/.el-select {
  width: 100% !important;
}
</style>
