<template>
  <div class="app-container">
    <calendar ref="postPlan" :eventsTime="eventsTime" @initList="getList" />
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="受检部门：">
        <el-cascader
          v-model="queryParams.checkedDeptId"
          :options="deptTreeList"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="工作组：">
        <el-input
          v-model="queryParams.checkGroupName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="检查小组：">
        <el-input
          v-model="queryParams.checkTeamName"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <!-- <el-form-item label="被检查部门：">
          <el-input
            v-model="queryParams.checkWorkgroupId"
            placeholder="请输入"
            clearable
          />
        </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      border
      v-loading="loading"
      :data="postList"
      :span-method="objectSpanMethod"
    >
    <el-table-column label="序号" align="center" width="50" prop="index">
        <template slot-scope="{ row }">
          <span>{{ row.index || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="计划名称"
        show-overflow-tooltip
        align="center"
        min-width="250px"
        prop="name"
      >
        <template slot-scope="{ row }">
          <span>{{ row.name || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="计划内容"
        show-overflow-tooltip
        align="center"
        min-width="200px"
        prop="content"
      >
        <template slot-scope="{ row }">
          <span>{{ row.content || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="工作组"
        show-overflow-tooltip
        align="center"
        min-width="160px"
        prop="checkGroupName"
      >
        <template slot-scope="{ row }">
          <span>{{ row.checkGroupName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="检查小组"
        show-overflow-tooltip
        align="center"
        min-width="120px"
        prop="checkTeamName"
      >
        <template slot-scope="{ row }">
          <span>{{ row.checkTeamName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="检查人员"
        align="center"
        show-overflow-tooltip
        min-width="220px"
        prop="checkUserName"
      >
        <template slot-scope="{ row }">
          <span>{{ checkedUserNames(row.checkUserChildren) || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="受检部门"
        show-overflow-tooltip
        align="center"
        min-width="140px"
        prop="checkedDeptName"
      >
        <template slot-scope="{ row }">
          <span>{{ row.checkedDeptName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="受检岗位"
        show-overflow-tooltip
        align="center"
        min-width="280px"
        prop="checkedPostNames"
      >
        <template slot-scope="{ row }">
          <span>{{ row.checkedPostNames || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="检查时间"
        align="center"
        min-width="220px"
        prop="checkedTimeView"
      >
        <template slot-scope="{ row }">
          <span>{{ row.checkedTimeView || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核状态"
        align="center"
        prop="status"
        min-width="100px"
      >
        <template slot-scope="{ row }">
          <span :style="{ color: statusColor[row.status] }">{{
            status[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="160"
        fixed="right"
        prop="operation"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleCheck('check', '查看', scope.row)"
            v-hasPermi="['postCheck:postPlan:query']"
            >查看</el-button
          >
          <el-button
            type="text"
            v-if="scope.row.status === 3"
            @click="publish(scope.row)"
            v-hasPermi="['postCheck:postPlan:query']"
            >发布</el-button
          >
            <!--v-if="scope.row.status !== 3"-->
          <el-dropdown
            size="mini"
            v-if="scope.row.status === 3 || scope.row.publish > 0"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >邮件通知</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleAuditor"
                >检查人</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="670px"
      @close="cancel"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        style="padding: 0 50px; height: 500px; overflow: auto"
        :disabled="type === 'check'"
      >
        <el-form-item label="计划名称：">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="计划内容：">
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 8 }"
            placeholder="请输入"
            v-model="form.content"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="工作组：">
          <el-select
            v-model="form.checkGroupId"
            placeholder="请选择"
            style="width: 100%"
            @change="handleGroupId"
          >
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查小组：">
          <el-select
            v-model="form.checkTeamId"
            placeholder="请选择"
            style="width: 100%"
            @change="handelTeam"
          >
            <el-option
              v-for="item in teamList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查人员：">
          <el-select
            v-model="form.checkUserChildren"
            placeholder="请选择"
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="0">
          <div
            v-for="(edit, index) in form.children"
            :key="index"
            class="form-list"
          >
            <div class="form-item">
              <el-form-item label="受检部门：">
              <el-form-item label="检查时间：">
                <el-date-picker
                  style="width: 100%; margin-bottom: 10px"
                  v-model="edit.dateRange"
                  type="daterange"
                  range-separator="至"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
                <el-cascader
                  v-model="edit.checkedDeptId"
                  :options="deptTreeList"
                  @change="(id) => handleChange(id, index)"
                  style="width: 100%; margin-bottom: 10px"
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="受检岗位：">
                <el-select
                  v-model="edit.checkedPostId"
                  placeholder="请选择"
                  multiple
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in edit.options"
                    :key="item.postId"
                    :label="item.postName"
                    :value="item.postId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="add_button" v-if="type !== 'check'">
              <span
                v-if="form.children.length !== 1"
                @click="handleDelItmes(index)"
                class="el-icon-remove"
              />
              <span
                v-if="form.children.length === index + 1"
                class="el-icon-circle-plus"
                @click="addItem"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="未通过原因：" prop="status" v-if="textarea2">
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 8 }"
            placeholder="请输入"
            v-model="textarea2"
            disabled
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="type !== 'check'">
        <el-button type="primary" @click="submitForm">提交审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPostPlan,
  getPostPlan,
  delPostPlan,
  addPostPlan,
  updatePostPlan,
  publish,
} from "@/api/postInspectionPlanning/jobPlan.js";
import {
  listGroupList,
  getDeptTree,
  getOptionselect,
  getTeamListByGroupId,
  getTeamUserByTeamId,
} from "@/api/postInspectionPlanning/teamManagement.js";
import {
  sendMailFile,
} from "@/api/postInspectionPlanning/projectManagement.js";

import calendar from "./calendar.vue";

export default {
  components: {
    calendar,
  },
  data() {
    return {
      eventsTime: [],
      type: "",
      groupList: [],
      teamList: [],
      userList: [],
      deptTreeList: [],
      value1: "",
      value: new Date(),
      textarea2: "",
      active: 0,
      establishDialog: false,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      status: {
        1: "待审核",
        2: "审核中",
        3: "通过",
        4: "驳回",
      },
      statusColor: {
        1: "#cdd152",
        2: "#61dd83",
        3: "#61dd83",
        4: "red",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        checkGroupName: "",
        checkTeamName: "",
        checkedDeptId: [],
      },
      // 表单参数
      form: {
        name: "",
        content: "",
        checkGroupId: "",
        checkUserChildren: [],
        checkWorkgroupId: "",
        statusHrUserId: "",
        createTime: "",
        checkTeamId: "",
        dateRange: [],
        children: [
          {
            checkedDeptId: [],
            options: [],
            checkedPostId: [],
          },
        ],
      },
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" },
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        ],
      },
      rowId: "",
    };
  },
  created() {
    // this.getList();
    // listPlanInfoUser()
    // listPostPlan()
    // listPostPlanInfo()
    this.getGroupList();
    this.getDeptTree();
  },
  computed: {
    checkedUserNames() {
      return (userNameList) => {
        return userNameList.map((item) => item.checkedUserName).join(",")
      };
    },
  },
  methods: {
    // 发送邮件
    handleCommand(command, row) {
      const params = {
        content: "",
        serviceId: row.id,
        serviceType: "",
      };
      this.$confirm("是否发送？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          switch (command) {
            case "handleAuditor":
              params.serviceType = "plan_checked_user";
              sendMailFile(params).then(() => {
                this.$modal.msgSuccess("发送成功");
              });
              break;
            default:
              break;
          }
        })
        .catch(() => false);
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const fields = [
        "name",
        "content",
        "checkGroupName",
        "checkTeamName",
        "checkUserName",
        "status",
        "index",
        "operation",
      ];
      if (fields.includes(column.property)) {
        const cellValue = row["checkTeamId"];
        if (cellValue && fields.includes(column.property)) {
          const prevRow = this.postList[rowIndex - 1];
          let nextRow = this.postList[rowIndex + 1];
          if (prevRow && prevRow["checkTeamId"] === cellValue) {
            return { rowspan: 0, colspan: 0 };
          } else {
            // return { rowspan: row.rowspan, colspan: 1 }
            let countRowspan = 1;
            while (nextRow && nextRow["checkTeamId"] === cellValue) {
              nextRow = this.postList[++countRowspan + rowIndex];
            }
            if (countRowspan > 1) {
              return { rowspan: countRowspan, colspan: 1 };
            }
          }
        }
      }
    },
    publish(row) {
      publish({ id: row.id }).then(() => {
        this.$modal.msgSuccess("发布成功");
      });
    },
    handleDelItmes(index) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.form.children.splice(index, 1);
        })
        .catch(() => {
          // 取消后退出
        });
    },

    addItem() {
      this.form.children.push({
        checkedDeptId: "",
        options: [],
        checkedPostId: [],
      });
    },
    getDeptTree() {
      getDeptTree().then((data) => {
        this.deptTreeList = data.data;
      });
    },
    getParentList(keyNmame, code, tree) {
      let arr = []; //要返回的数组
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i];
        arr = [];
        arr.push(item[keyNmame]); //保存当前节点id
        if (code == item[keyNmame]) {
          //判断当前id是否是默认id
          return arr; //是则退出循环、返回数据
        } else {
          //否则进入下面判断，判断当前节点是否有子节点数据
          if (item.children && item.children.length > 0) {
            //合并子节点返回的数据
            arr = arr.concat(this.getParentList(keyNmame, code, item.children));
            if (arr.includes(code)) {
              //如果当前数据中已包含默认节点，则退出循环、返回数据
              return arr;
            }
          }
        }
      }
    },
    getGroupList() {
      listGroupList().then((data) => {
        this.groupList = data.data;
      });
    },
    async handleGroupId(id) {
      this.form.checkTeamId = "";
      if (id) {
        const { data } = await getTeamListByGroupId(id);
        this.teamList = data;
      }
    },
    async handelTeam(id) {
      if (id) {
        this.form.checkUserChildren = [];
        const { data } = await getTeamUserByTeamId(id);
        this.userList = data;
      }
    },
    getOptionselect(id, index) {
      getOptionselect(id).then((data) => {
        this.form.children[index].options = data.data;
      });
    },
    handleChange(arr, index) {
      this.form.children[index].options = [];
      this.form.children[index].checkedPostId = [];
      const id = arr[arr.length - 1];
      this.getOptionselect(id, index);
    },
    /** 查询岗位列表 */
    getList({ dateRange, type }) {
      this.loading = true;
      const checkedDeptId = this.queryParams.checkedDeptId[this.queryParams.checkedDeptId.length - 1];
      listPostPlan(this.addDateRange({...this.queryParams, checkedDeptId}, dateRange)).then(
        (response) => {
          this.postList = response.rows;
          if (type) {
            this.eventsTime = [
              ...new Set(
                this.postList.map((item) => item.checkedTimeView.split(" 至 ")[0])
              ),
            ];
          }
        const teamId = [
          ...new Set(this.postList.map((item) => item.id)),
        ];
        this.postList.forEach((item) => {
          item.index = teamId.findIndex((i) => item.id === i) + 1;
        });
          this.total = teamId.length;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelEstablish() {
      this.establishDialog = false;
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form;
      this.textarea2 = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.$refs.postPlan.initDate();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = this.$options.data().queryParams;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.establishDialog = true;
    },
    /** 查看 */
    handleCheck(type, title, row) {
      this.type = type;
      this.title = title;
      if (!row) {
        this.open = true;
        return;
      }
      this.rowId = row.id;
      getPostPlan(row.id).then((data) => {
        const { statusHr, statusIcfa, reasonHr, reasonIcfa } = data.data;
        this.textarea2 =
          statusHr === 4 ? reasonHr : statusIcfa === 4 ? reasonIcfa : "";
        const children = [];
        const result = data.data.children;
        const depId = [...new Set(result.map((item) => item.checkedDeptId))];
        const checkUserChildren = row.checkUserChildren.map(
          (item) => item.checkedUserId
        );
        depId.forEach((item) => {
          const find = result.find(data => data.checkedDeptId === item);
          const dateRange = [find.startTime, find.endTime];
          getOptionselect(item).then((res) => {
            const checkedPostId = result
              .filter((i) => i.checkedDeptId === item)
              .map((i) => i.checkedPostId);
            children.push({
              checkedDeptId: this.getParentList(
                "value",
                item,
                this.deptTreeList
              ),
              options: res.data,
              checkedPostId,
              dateRange
            });
          });
        });
        this.handleGroupId(data.data.checkGroupId);
        this.handelTeam(data.data.checkTeamId);
        this.form = {
          ...this.form,
          ...data.data,
          children,
          checkUserChildren
        };
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const result = [];
          this.form.children.forEach((item) => {
            const checkedDeptId =
              item.checkedDeptId[item.checkedDeptId.length - 1];
            item.checkedPostId.forEach((checkedPostId) => {
              result.push({
                checkedDeptId,
                checkedPostId,
              });
            });
          });
          const startTime = this.form.dateRange[0];
          const endTime = this.form.dateRange[1];
          const checkUserChildren = this.form.checkUserChildren.map((item) => ({
            checkedUserId: item,
          }));
          const params = {
            ...this.form,
            children: result,
            startTime,
            endTime,
            checkUserChildren,
          };
          delete params.dateRange;
          if (this.type === "edit") {
            updatePostPlan({ ...params, id: this.rowId }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$refs.postPlan.initDate();
            });
          } else {
            addPostPlan(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$refs.postPlan.initDate();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delPostPlan(postIds);
        })
        .then(() => {
          this.$refs.postPlan.initDate();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
.form-list {
  display: flex;
  position: relative;
  border: solid 1px #1352b6;
  margin-bottom: 10px;
  padding-top: 10px;
  padding-right: 10px;
  border-radius: 8px;
  .form-item {
    flex: 1;
    // border: solid 1px;
    // padding: 10px 20px 10px 0px;
    // border-radius: 8px;
    margin-bottom: 10px;
  }
  .add_button {
    position: absolute;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin-left: 10px;
    margin-bottom: 10px;
    right: -35px;
    height: 80px;
    .el-icon-circle-plus {
      font-size: 26px;
      color: #67c23a;
      cursor: pointer;
    }
    .el-icon-remove {
      font-size: 26px;
      color: #f56c6c;
      cursor: pointer;
    }
  }
}
</style>
