<template>
  <div class="common-box">
    <!--条件-->
    <el-form
      :model="listQuery"
      ref="queryForm"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="审批业务编码">
        <el-input
          v-model="listQuery.bizCode"
          placeholder="请输入审批业务编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="审批业务名称">
        <el-input
          v-model="listQuery.bizName"
          placeholder="请输入审批业务名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getData('search')">查询</el-button>
        <el-button @click="reset()">清空</el-button>
      </el-form-item>
    </el-form>
    <div class="right-button">
      <el-button
        class="lake-Blue"
        type="primary"
        icon="el-icon-plus"
        @click="handleAddOrEdit(null, 'create')"
        >新增</el-button
      >
    </div>
    <!--列表-->
    <div>
      <el-table
        v-loading="listLoading"
        element-loading-text="加载中"
        :data="list"
        fit
        stripe
        border
      >
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column label="审批业务编码" prop="bizCode" />
        <el-table-column label="审批业务名称" prop="bizName" />
        <el-table-column label="状态" prop="enabFlag">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.enabFlag === '1'">
              停用
            </el-tag>
            <el-tag type="success" v-if="scope.row.enabFlag === '0'">
              启用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              class="cyan"
              type="text"
              @click="handleAddOrEdit(scope.row, 'update')"
              >编辑</el-button
            >

            <!-- <el-button
              icon="el-icon-delete"
              class="color: red"
              type="text"
              @click="handleDelete(scope.row, 'deleted')"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <yl-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getData"
    />

    <!--添加/修改-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="1300px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="业务类型名称" prop="bizName">
          <el-input v-model.trim="temp.bizName" />
        </el-form-item>
        <el-form-item label="驳回位置">
          <el-radio-group v-model="temp.rejtLoc">
            <el-radio label="0">发起者</el-radio>
            <el-radio label="1">上一级</el-radio>
            <el-radio label="2">终止审批</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model.trim="temp.dscr" type="textarea" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.enabFlag">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发起位置">
          <el-radio-group v-model="temp.abinitio">
            <el-radio label="0">顺延审批</el-radio>
            <el-radio label="1">从头开始</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批级别" :required="true">
          <div style="margin-bottom: 10px">
            <el-button
              plain
              type="primary"
              class="el-icon-plus"
              @click.prevent="addRow()"
              >添加行</el-button
            >

            <el-button
              plain
              type="danger"
              class="el-icon-minus"
              @click.prevent="delData()"
              >删除行</el-button
            >
          </div>
          <el-table
            id="table"
            ref="table"
            v-loading="listLoading"
            :data="lvList"
            element-loading-text="Loading"
            fit
            stripe
            border
            @selection-change="selectRow"
          >
            <template slot="empty">
              <img src="@/assets/nopage.png" alt />
              <p>暂无数据</p>
            </template>
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column label="级别">
              <template slot-scope="scope">
                第{{ scope.row.lv }}级审批
              </template>
            </el-table-column>
            <el-table-column label="名称">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.lvName"
                  style="width: 150px; margin-right: 10px"
                ></el-input>
              </template>
            </el-table-column>
            <!-- <el-table-column label="用户">
              <template slot-scope="scope">
                <el-form-item label-width="0">
                  <el-input
                    disabled
                    v-model="scope.row.loginId"
                    style="width: 150px; margin-right: 10px"
                  ></el-input
                  ><el-button
                    type="primary"
                    plain
                    @click="chooseUsers(scope.row.lv)"
                    >选择用户</el-button
                  >
                </el-form-item>
              </template>
            </el-table-column> -->

            <el-table-column label="角色">
              <template slot-scope="scope">
                <el-form-item label-width="0">
                  <el-input
                    disabled
                    v-model="scope.row.roleId"
                    style="width: 150px; margin-right: 10px"
                  ></el-input
                  ><el-button
                    type="primary"
                    plain
                    @click="chooseRoles(scope.row.lv)"
                    >选择角色</el-button
                  >
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="commitData()">确认</el-button>
      </div>
    </el-dialog>

    <!--打开用户对话框-->
    <el-dialog
      v-if="dialogUsersFormVisible"
      title="选择用户"
      :visible.sync="dialogUsersFormVisible"
      width="1000px"
    >
      <users
        @usersClose="usersClose"
        @usersSubmit="usersSubmit"
        :userRadio="loginId"
      ></users>
    </el-dialog>

    <!--打开角色对话框-->
    <el-dialog
      v-if="dialogRolesFormVisible"
      title="选择角色"
      :visible.sync="dialogRolesFormVisible"
      width="1000px"
    >
      <roles
        @rolesClose="rolesClose"
        @rolesSubmit="rolesSubmit"
        :roleRadio="roleId"
      ></roles>
    </el-dialog>
  </div>
</template>

<script>
import {
  setApprove,
  getApprove,
  getApproveLv
} from "@/api/system/approveConfig";
import ylPagination from "@/components/yl-pagination";
import users from "@/views/page/system/approveConfig/components/users";
import roles from "@/views/page/system/approveConfig/components/roles";

export default {
  components: {
    ylPagination,
    users,
    roles
  },

  watch: {},

  data() {
    return {
      // 回显用户
      loginId: "",
      // 回显角色
      roleId: "",
      // 用户对话框
      dialogUsersFormVisible: false,
      // 角色对话框
      dialogRolesFormVisible: false,
      // 第几行
      rowId: "",
      selectlistRow: [],
      // 审批级别
      lvList: [],
      list: [], //列表
      total: 0, //分页
      listLoading: false,
      listQuery: {
        //条件查询
        bizName: "",
        current: 1,
        size: 10,
        bizCode: "",
        route: ""
      },
      dialogFormVisible: false, //是否对话框
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加"
      },
      temp: {},
      rules: {
        bizName: [
          {
            required: true,
            message: "审批业务名称不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 选择用户对话框
    chooseUsers(index) {
      this.rowId = index;
      this.loginId = this.lvList[this.rowId - 1].loginId;
      this.dialogUsersFormVisible = true;
    },

    // 关闭用户对话框
    usersClose() {
      this.dialogUsersFormVisible = false;
    },

    // 获取到选中的用户
    usersSubmit(userRadio) {
      this.lvList[this.rowId - 1].loginId = userRadio;
      this.dialogUsersFormVisible = false;
    },

    // 选择角色对话框
    chooseRoles(index) {
      this.rowId = index;
      this.roleId = this.lvList[this.rowId - 1].roleId;
      this.dialogRolesFormVisible = true;
    },

    // 关闭角色对话框
    rolesClose() {
      this.dialogRolesFormVisible = false;
    },

    // 获取到选中的角色
    rolesSubmit(roleRadio) {
      this.lvList[this.rowId - 1].roleId = roleRadio;
      this.dialogRolesFormVisible = false;
    },

    // 获取表格选中时的数据
    selectRow(val) {
      this.selectlistRow = val;
    },

    // 增加行
    addRow() {
      if (this.lvList.length >= 20) {
        this.$message({
          message: "最多只能添加20行",
          type: "warning"
        });
        return false;
      }
      let num = this.lvList.length + 1;
      var list = {
        lv: num,
        loginId: "",
        roleId: "",
        lvName: ""
      };
      this.lvList.push(list);
    },

    // 删除选中行
    delData() {
      if (this.selectlistRow.length == 0) {
        this.$message({
          message: "请先选择要删除的行",
          type: "warning"
        });
        return false;
      }
      for (let i = 0; i < this.selectlistRow.length; i++) {
        let val = this.selectlistRow;
        val.forEach((val, index) => {
          this.lvList.forEach((v, i) => {
            if (val.lv == v.lv) {
              this.lvList.splice(i, 1);
            }
          });
        });
      }
      this.lvList.forEach((v, i) => {
        v.lv = i + 1;
      });
      this.selectlistRow = [];
    },

    // 重置页面
    reset() {
      this.listQuery.bizCode = "";
      this.listQuery.bizName = "";
      this.getData();
    },

    //获取列表数据
    getData(type) {
      if (type == "search") {
        this.listQuery.current = 1;
      }
      this.listLoading = true;
      getApprove(this.listQuery)
        .then(response => {
          this.list = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch(err => {
          this.listLoading = false;
        });
    },

    //提交表单数据
    commitData() {
      if (this.lvList.length == 0) {
        this.$message({
          message: "至少需要添加一条审批级别",
          type: "warning"
        });
        return false;
      }
      if (this.lvList.length > 0) {
        this.lvList.forEach(item => {
          if (!item.loginId && !item.roleId) {
            this.$message({
              message: "请选择用户或者角色",
              type: "warning"
            });
            throw new Error("请选择用户或者角色");
          }
        });
      }
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.temp.levels = this.lvList;
            if (this.temp.bizName == "资质审批") {
              this.temp.route = "qualificationAppr";
            } else if (this.temp.bizName == "药品目录审批") {
              this.temp.route = "drugCataAppr";
            } else if (this.temp.bizName == "药品采购计划审批") {
              this.temp.route = "drugPurchasePlan";
            } else if (this.temp.bizName == "药品退货审批") {
              this.temp.route = "drugReturn";
            } else if (this.temp.bizName == "调价申请审批") {
              this.temp.route = "priceUpApply";
            } else if (this.temp.bizName == "申领审批") {
              this.temp.route = "applyAppr";
            }
            console.log(this.temp, "temp");
            setApprove(this.temp).then(response => {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getData();
            });
          });
        }
      });
    },

    // 打开添加/修改对话框
    handleAddOrEdit(row, type) {
      this.lvList = [];
      //修改对话框
      if (type === "update") {
        getApproveLv({ prcsCode: row.prcsCode }).then(response => {
          if (response.data.length > 0) {
            response.data.forEach(item => {
              this.lvList.push({
                lv: item.lv,
                loginId: item.loginId,
                roleId: item.roleId,
                lvName: item.lvName
              });
            });
          }
        });
        this.temp = {
          id: row.id,
          bizCode: row.bizCode,
          bizName: row.bizName,
          rejtLoc: row.rejtLoc,
          dscr: row.dscr,
          levels: this.lvList,
          enabFlag: row.enabFlag,
          type: "updt",
          abinitio: row.abinitio
        };
      } else {
        this.temp = {
          id: "",
          bizCode: "",
          bizName: "",
          rejtLoc: "0",
          dscr: "",
          enabFlag: "0",
          levels: [],
          type: "add",
          abinitio: ""
        };
      }
      this.dialogStatus = type;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    }

    //删除
    // handleDelete(row, status) {
    //   this.$confirm("确认删除", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then(() => {
    //     this.temp = {
    //       id: row.id,
    //       type: "del",
    //     };
    //     setApprove(this.temp).then((response) => {
    //       this.$message({
    //         message: "操作成功",
    //         type: "success",
    //       });
    //       // 解决element el-pagination分页最后一页数据清空了页码显示正确，但是列表为空
    //       const totalPage = Math.ceil((this.total - 1) / this.listQuery.size);
    //       const currentPage =
    //         this.listQuery.current > totalPage
    //           ? totalPage
    //           : this.listQuery.current;
    //       this.listQuery.current = currentPage < 1 ? 1 : currentPage;
    //       this.getData();
    //     });
    //   });
    // },
  }
};
</script>

<style lang="scss" scoped>
#table {
  .el-form-item {
    margin-bottom: 0 !important;
  }
}
</style>
