<template>
  <div class="testdiv">
    <div id="topArea" class="divborder newSearchDiv" style="margin:0px;">
      <div class="searchBtn">
        <Button
          id="addbtn"
          type="success"
          icon="md-add-circle"
          class="twoWord"
          @click="add()"
          >{{ $t("1002") }}</Button
        >
        <Button
          id="editbtn"
          type="warning"
          class="twoWord"
          @click="edit()"
          icon="ios-create-outline"
          >{{ $t("1003") }}</Button
        >
        <Button
          id="deletebtn"
          type="error"
          icon="md-close-circle"
          class="twoWord"
          @click="Delete()"
          >{{ $t("1004") }}</Button
        >
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        id="tablemiddle"
        highlight-row
        class="tableClass"
        :data="tableData1"
        :columns="tableColumns1"
        @on-current-change="handleRowChange"
      ></Table>
      <div id="pageBottom" class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            show-elevator
            show-sizer
            show-total
            @on-change="changePage"
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10, 20, 30, 40, 100]"
          ></Page>
        </div>
      </div>
      <!-- 添加/编辑对话框 -->
      <Modal
        :title="$t(1002)"
        v-model="addmodal"
        :styles="{ width: '650px' }"
        class="newModalClass"
      >
        <p slot="header">
          <span v-if="type == 1">{{ $t("1002") }}</span>
          <span v-if="type == 2">{{ $t("1003") }}</span>
        </p>
        <!-- 流程名称 -->
        <div class="filter">
          <label>
            <i>*</i>
            {{ $t(1000042) }}：
          </label>
          <Input
            clearable
            id="input1"
            type="text"
            v-model="addobj.name"
            class="searchInput"
          />
        </div>
        <!-- 应用部门 -->
        <div class="filter">
          <label>
            <i>*</i>
            {{ $t(950281) }}：
          </label>
          <Select
            clearable
            label-in-value
            id="section_id"
            class="searchSelect"
            @on-change="init_dept_depart"
            v-model="addobj.section_id"
          >
            <Option
              v-for="item in departmentlist"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</Option
            >
          </Select>
        </div>
        <!-- 流程说明 -->
        <div class="filter">
          <label>{{ $t(1000043) }}：</label>
          <Input
            clearable
            id="input1"
            type="text"
            v-model="addobj.description"
            class="searchInput"
          />
        </div>
        <!-- 流程设置 -->
        <div class="modal-body">
          <label>
            <i>*</i>
            {{ $t(1000044) }}：
          </label>
          <div class="approval_c" v-for="(item, index) in map_c" :key="index">
            <!-- 里边的每一个div 盒子 -->
            <div class="top-inner-row">
              <ul>
                <!-- 1: 审批人 -->
                <li class="first">
                  {{ $t("1077") }}
                  <b class="color">{{ index + 1 }}</b> {{ $t("1226") }}：
                </li>
                <!-- 2：下拉框选择 -->
                <li class="second">
                  <Select
                    filterable
                    label-in-value
                    size="default"
                    style="width:130px"
                    @on-change="init_dept_user"
                    v-model="item.approval_usertype"
                  >
                    <Option
                      v-for="(val, key) in approverList"
                      :key="key"
                      :value="val.Value"
                      @click.native="getindex(index)"
                      v-show="flag"
                      >{{ val.Label }}</Option
                    >
                  </Select>
                </li>
                <!-- 3：单选 -->
                <li>
                  <RadioGroup class="radiobox" v-model="item.approval_type">
                    <Radio :label="1"
                      ><span>{{ $t("600322") }}</span></Radio
                    >
                    <Radio :label="2"
                      ><span>{{ $t("600323") }}</span></Radio
                    >
                  </RadioGroup>
                </li>
                <!-- 4： 关闭按钮 -->
                <li class="images">
                  <img
                    class="header-close"
                    @click="deleteView"
                    src="@/assets/images/task_close.png"
                  />
                </li>
                <!-- 指定岗位 -->
                <li class="li-bottom" v-if="item.approval_usertype == 1">
                  <Select
                    filterable
                    multiple
                    size="default"
                    style="width:500px"
                    v-model="item.approval_usergroupid"
                  >
                    <Option
                      v-for="(i, k) in positionList"
                      :key="k"
                      :value="i.id"
                      >{{ i.title }}</Option
                    >
                  </Select>
                </li>
                <!-- 指定人 -->
                <li class="li-bottom" v-if="item.approval_usertype == 2">
                  <Select
                    filterable
                    multiple
                    size="default"
                    style="width:500px"
                    v-model="item.approval_usergroupid"
                  >
                    <Option v-for="(i, k) in crewList" :key="k" :value="i.id">{{
                      i.name
                    }}</Option>
                  </Select>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div slot="footer" class="footer">
          <div>
            <Button
              type="primary"
              size="large"
              @click="asyncAdd"
              v-text="$t(1002)"
              >{{ $t("1002") }}</Button
            >
          </div>
          <div>
            <Button
              type="text"
              size="large"
              @click="cancel()"
              v-text="$t(1033)"
              >{{ $t("1033") }}</Button
            >
            <Button
              type="primary"
              v-if="type == 1"
              size="large"
              @click="asyncConfirm(1)"
              class="myBtn"
              :loading="loading"
            >
              <span v-if="!loading">{{ $t(1011) }}</span>
              <span v-else>Loading...</span>
            </Button>
            <Button
              type="primary"
              v-if="type == 2"
              size="large"
              @click="asyncConfirm(2)"
              :loading="loading"
            >
              <span v-if="!loading">{{ $t(1011) }}</span>
              <span v-else>Loading...</span>
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import axios from "@/libs/api.request";
export default {
  data() {
    return {
      loading: false,
      flag: true,
      itemindex: 0,
      result: {},
      approveType: "",
      page: 1,
      pagesize: 10,
      total: 0,
      type: 0, // type 为 1 是添加操作 type 为 2 是修改操作
      addmodal: false, // 对话框默认隐藏
      name: "", //  流程名称
      addFlow: "", // 流程设置
      section_id: "", // 应用部门
      description: "", // 流程说明
      detailobj: {},
      map_c: [], // 数组
      tableData1: [], // Table 表格数据
      departmentlist: [], // 应用部门数组
      addobj: {}, // 弹出框中表单对象
      positionList: [], // 指定岗位数据
      crewList: [], // 指定人数据
      approverList: [
        {
          Value: 0,
          Label: this.$t("1014")
        },
        {
          Value: 1,
          Label: this.$t("1227")
        },
        {
          Value: 2,
          Label: this.$t("1228")
        }
      ],
      tableColumns1: [
        {
          type: "sort",
          title: this.$t(1008),
          width: 80,
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          }
        },
        {
          title: this.$t(1000042),
          key: "name"
        },
        {
          title: this.$t(950281),
          key: "section_name"
        },
        {
          title: this.$t(100040),
          key: "creator_name"
        },
        {
          title: this.$t(1020),
          key: "create_time"
        },
        {
          title: this.$t(200054),
          render: (h, params) => {
            return h("div", [
              h(
                "i-switch",
                {
                  props: {
                    value: params.row.status == 1
                  },
                  on: {
                    "on-change": status => {
                      let code = status ? 1 : 0;
                      this.axios
                        .request({
                          url:
                            "/esop/EsopProcess/UpdateProcessStatus?id=" +
                            params.row.id +
                            "&status=" +
                            code,
                          methods: "get"
                        })
                        .then(res => {
                          if (res.data.ret === 1) {
                            this.$Message.success(this.$t(400039));
                          } else {
                            this.$Message.error(this.$t(res.data.msg));
                          }
                        });
                    }
                  }
                },
                [
                  h("span", {
                    slot: "open",
                    domProps: {
                      // DOM 属性
                      innerHTML: this.$t(1229)
                    }
                  }),
                  h("span", {
                    slot: "close",
                    domProps: {
                      // DOM 属性
                      innerHTML: this.$t(1230)
                    }
                  })
                ]
              )
            ]);
          }
        }
      ]
    };
  },
  created() {
    this.search();
    this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
  },
  mounted() {
    // 获取应用部门下拉列表
    this.addDepartmentchange();
  },
  methods: {
    search() {
      this.page = 1;
      this.pagesize = 10;
      this.tableSearch();
    },
    tableSearch() {
      this.detailobj = {};
      var params = {
        page: this.page,
        pagesize: this.pagesize
      };
      axios
        .request({
          url: "/esop/EsopProcess/GetProcessPagedList",
          params,
          method: "get"
        })
        .then(res => {
          if (res.data.ret === 1) {
            this.total = res.data.total;
            this.tableData1 = res.data.data;
            this.page = res.data.page;
          }
        });
    },
    // 监听添加事件
    add() {
      this.type = 1; // 设置 type 为 1 表示是添加操作
      this.addmodal = true;
      this.addobj = {
        name: "",
        section_id: "",
        description: ""
      };
      this.map_c = [];
      this.map_c.push({
        // 默认显示出来一个选择框
        approval_usertype: "",
        approval_type: 1,
        approval_usergroupid: ""
      });
    },
    // 弹框确定事件
    asyncConfirm(type) {
      if (!this.addobj.name) {
        this.$Message.warning(this.$t(1000045));
        return false;
      } else if (!this.addobj.section_id) {
        this.$Message.warning(this.$t(1000047));
        return false;
      }
      // 对审批人表单验证
      if (this.map_c.length == 0) {
        this.$Message.warning(this.$t("1000050"));
        return false;
      }
      let group = [];
      let code = 0;
      this.map_c.forEach((item, index) => {
        if (item.approval_usertype === "") {
          code = 1;
        }
        if (item.approval_type === "") {
          code = 1;
        }
        if (item.approval_usergroupid.length === 0) {
          code = 1;
        }
        group.push({
          approval_usertype: item.approval_usertype,
          approval_type: item.approval_type,
          approval_usergroupid:
            item.approval_usergroupid.length === 0
              ? ""
              : item.approval_usergroupid.join()
        });
      });
      if (code === 1) {
        this.$Message.warning(this.$t("1000049"));
        return false;
      }
      // 组装请求参数
      var data = {
        id: this.detailobj.id !== undefined ? this.detailobj.id : "", // 获取当前id值
        name: this.addobj.name, // 流程名称
        description:
          this.addobj.description != undefined ? this.addobj.description : "", // 流程说明
        section_id: this.addobj.section_id, //  应用部门
        groups: group
      };
      // type 为 1 添加 type 为 2 修改
      this.loading = true;
      if (type == 1) {
        this.axios
          .request({
            url: "/esop/EsopProcess/AddProcess",
            data,
            method: "post"
          })
          .then(res => {
            this.loading = false;
            if (res.data.ret === 1) {
              this.addmodal = false; // 隐藏对话框
              this.$Message.success(this.$t(1055)); // 提示用户
              this.page = 1;
              this.pagesize = 10;
              this.tableSearch(); // 刷新列表
              this.name = "";
              this.description = "";
              this.section_id = "";
            } else {
              this.$Message.error(this.$t(res.data.msg));
            }
          })
          .catch(err => {
            this.loading = false;
          });
      } else if (type == 2) {
        this.axios
          .request({
            url: "/esop/EsopProcess/UpdateProcess",
            data,
            method: "post"
          })
          .then(res => {
            this.loading = false;
            if (res.data.ret === 1) {
              this.addmodal = false; // 隐藏
              this.$Message.success(this.$t(1060)); // 提示
              this.tableSearch(); // 刷新
              this.name = "";
              this.description = "";
              this.section_id = "";
            } else {
              this.$Message.error(this.$t(res.data.msg));
            }
          })
          .catch(err => {
            this.loading = false;
          });
      }
    },
    // 弹框取消事件
    cancel() {
      this.addobj = {
        name: "",
        section_id: "",
        description: ""
      }; // 清空
      this.addmodal = false; // 隐藏
    },
    // 修改事件
    edit() {
      this.map_c = [];
      if (!this.detailobj.id) {
        // 如果当前没有选中某一行，则跳出函数给用户提示
        this.$Message.error(this.$t(1043));
        return false;
      }
      this.addmodal = true;
      this.type = 2; // type 为 2 表示修改
      // 调用编辑接口
      let params = { id: this.detailobj.id };
      axios
        .request({
          url: "/esop/EsopProcess/GetProcessItem",
          params,
          method: "get"
        })
        .then(res => {
          if (res.data.ret === 1) {
            let result = res.data.data;
            // 赋值操作
            this.addobj.name = result.name; // 流程名称
            this.addobj.description = result.description; // 流程说明
            this.addobj.section_id = result.section_id; // 应用部门
            // this.getStation(); // 获取指定岗位
            // this.getPerson(); // 获取指定人员
            this.map_c = [];
            Promise.all([this.getStation(), this.getPerson()])
              .then(() => {
                this.$nextTick(() => {
                  setTimeout(() => {
                    var arr = [];
                    if (Array.isArray(result.groups) && result.groups.length) {
                      result.groups.forEach((item, index) => {
                        let arr1 = {};
                        arr1.approval_type = item.approval_type;
                        arr1.approval_usertype = item.approval_usertype;
                        let idList =
                          item.approval_usergroupid != "" &&
                          item.approval_usergroupid != undefined &&
                          item.approval_usergroupid != null
                            ? item.approval_usergroupid.split(",")
                            : "";
                        if (idList != "") {
                          arr1.approval_usergroupid = idList.map(item => {
                            return parseInt(item);
                          });
                        } else {
                          arr1.approval_usergroupid = "";
                        }
                        arr.push(arr1);
                      });
                    }
                    this.map_c = arr;
                  }, 200);
                });
              })
              .catch(err => {
                // 抛出错误信息
              });
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 弹框应用部门切换事件
    init_dept_depart() {
      this.map_c = [];
      this.map_c.push({
        // 默认显示出来一个选择框
        approval_usertype: 0,
        approval_type: 1,
        approval_usergroupid: ""
      });
      this.getPerson();
      this.getStation();
    },
    // 监听弹框添加事件
    asyncAdd() {
      // 提交参数对象
      this.map_c.push({
        approval_usertype: "",
        approval_type: 1,
        approval_usergroupid: ""
      });
    },
    //  监听删除事件
    deleteView(index) {
      this.map_c.splice(index, 1);
    },
    // 删除事件
    Delete() {
      if (
        this.detailobj.id === undefined ||
        this.detailobj.id === null ||
        this.detailobj.id === ""
      ) {
        this.$Message.error(this.$t("1043"));
        return false;
      } else {
        this.$Modal.confirm({
          title: this.$t("1018"),
          content: "",
          width: "290px",
          closable: true,
          okText: this.$t("1004"),
          onOk: () => {
            let params = { id: this.detailobj.id };
            axios
              .request({
                url: "/esop/EsopProcess/DeleteProcess",
                params,
                method: "post"
              })
              .then(res => {
                if (res.data.ret === 1) {
                  this.$Message.success(this.$t("1058"));
                  this.page = 1;
                  this.tableSearch(); // 刷新列表
                } else {
                  this.$Message.error(this.$t(res.data.msg));
                  this.tableSearch(); // 刷新列表
                }
              });
          }
        });
      }
    },
    // 选中的Option变化时触发
    init_dept_user(value) {},
    getindex(index) {
      let sectionId = this.addobj.section_id;
      if (sectionId === undefined || sectionId === "") {
        this.$Message.warning(this.$t("400069"));
        this.map_c[index].approval_usertype = "";
        return false;
      }
      // 根据index 删除对应数组
      this.itemindex = index;
      this.map_c[index].approval_usergroupid = [];
    },
    // 开启highlight-row 后有效, 当前表格触发事件
    handleRowChange(currentRow, oldCurrentRow) {
      this.detailobj = currentRow;
    },
    changePage(value) {
      this.page = value;
      this.tableData1 = this.tableSearch(this.page, this.pagesize);
    },
    handlePageSize(value) {
      this.pagesize = value;
      this.tableData1 = this.tableSearch(this.page, this.pagesize);
    },
    // 获取指定岗位数据
    getStation() {
      let params = { sectionid: this.addobj.section_id };
      axios
        .request({
          url: "/config/projectuser/GetUserUserGroup",
          params,
          method: "get"
        })
        .then(res => {
          this.positionList = [];
          if (res.data.ret === 1) {
            this.positionList = res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 获取指定人员
    getPerson() {
      let params = { sectionid: this.addobj.section_id };
      axios
        .request({
          url: "/config/ProjectUser/getUserListsBySectionId",
          params,
          method: "get"
        })
        .then(res => {
          this.crewList = [];
          if (res.data.ret === 1) {
            this.crewList = res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 应用部门选中的Option变化时触发
    addDepartmentchange() {
      axios
        .request({
          url: "config/ProjectUser/getUserDepartment",
          method: "get"
        })
        .then(res => {
          this.departmentlist = [];
          if (res.data.ret === 1 && res.data.data.length !== 0) {
            this.departmentlist = res.data.data;
          } 
          // else {
          //   this.$Message.error(this.$t(res.data.msg));
          // }
        });
    }
  }
};
</script>
<style lang="less" scoped>
.footer {
  display: flex;
  justify-content: space-between;
}
.Settinginput {
  width: 395px;
}
.approval_c {
  border: 1px dashed #bbb;
  padding: 15px;
  margin: 12px 35px 10px 25px;
  border-radius: 4px;
}
.header-close {
  display: block;
  width: 12px;
  height: 12px;
  margin-left: 180px;
  cursor: pointer;
}
.top-inner-row {
  width: 560px;
  overflow: hidden;
  .first {
    margin-top: 7px;
  }
  .second {
    margin-left: -35px;
  }
  .radiobox {
    margin-top: 5px;
  }
  .images {
    margin-top: -15px;
    margin-left: 40px;
  }
}
.top-inner-row > ul > li {
  float: left;
  margin-right: 45px;
}
.color {
  color: red;
}
.li-bottom {
  margin-top: 10px;
}
.modal-body {
  max-height: 400px;
  overflow-y: scroll;
}
</style>


