<template>
  <!-- 会议申请 -->
  <div class="content-container">
    <div class="right-box">
      <div class="top">
        <el-form
          ref="form"
          :inline="true"
          :model="form"
          style="float: left; height: 45px"
        >
          <el-form-item label="关键字:">
            <el-input
              v-model="form.content"
              size="small"
              placeholder="请输入会议单号、会议名称"
              style="width: 220px"
            ></el-input>
          </el-form-item>

          <el-form-item label="申请部门:">
            <el-select
              v-model="form.registerDept"
              filterable
              clearable
              collapse-tags
              placeholder="请选择申请部门"
              size="small"
            >
              <el-option
                v-for="item in allDept"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="申请时间:">
            <el-date-picker
              v-model="form.purchaseTime"
              type="daterange"
              align="right"
              value-format="yyyy-MM-dd"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="queryProcess"
            style="margin-top: 4px"
            >查询</el-button
          >
        </el-form>

        <el-button
          type="primary"
          @click="orderRegister"
          icon="el-icon-plus"
          size="small"
          >会议申请</el-button
        >
      </div>
      <div class="table-div">
        <el-table
          :data="tableData"
          style="width: 100%"
          :style="{ width: '100%' }"
          height="100%"
          :header-cell-style="{
            background: 'rgba(250,250,250)',
            color: 'rgb(50,59,65)',
            height: '38px',
            textAlign: 'center',
          }"
        >
          <template slot="empty">
            <img src="@/assets/icon/null.png" alt="" />
            <p class="empty-p">暂无数据</p>
          </template>
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="60px"
          ></el-table-column>
          <el-table-column
            prop="processNumber"
            label="会议单号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="会议名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="roomName"
            label="地点"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="startTime"
            label="开始时间"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="endTime"
            label="结束时间"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="registerDeptName"
            label="申请部门"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>{{ getDeptName(row.registerDept) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="registerStaffName"
            label="申请人"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>{{
                getUserName(row.registerDept, row.registerStaff)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="registerTime"
            label="申请时间"
            align="center"
          ></el-table-column>
          <el-table-column prop="processState" label="流程状态" align="center">
            <template slot-scope="{ row }">
              <span>{{ getOrderStateNameById(row.processState) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                @click="queryOrderProcessById(scope.row, false)"
                icon="el-icon-tickets"
                title="查看"
                type="text"
                size="small"
                style="font-size: 16px"
              ></el-button>
              <el-button
                v-if="scope.row.processState == 1"
                @click="queryOrderProcessById(scope.row, true)"
                icon="el-icon-edit"
                title="修改"
                type="text"
                size="small"
                style="font-size: 16px"
              ></el-button>
              <el-button
                v-if="scope.row.processState == 1"
                @click="delOrderProcessById(scope.row)"
                icon="el-icon-delete"
                title="删除"
                type="text"
                size="small"
                style="font-size: 16px; color: red"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="pagination.current"
        :page-sizes="[20, 30, 50, 100, 200]"
        :page-size="pagination.size"
        :total="pagination.total"
        @size-change="changePaginationSize"
        @current-change="changePaginationCurrent"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    <!-- 详情 -->
    <el-dialog
      class="tf-dialog"
      :title="title"
      :visible.sync="dialogFormVisible"
      width="1200px"
      top="60px"
      style="padding: 10px"
    >
      <process-order
        v-if="dialogFormVisible"
        ref="merge"
        :orderName="orderName"
        :orderCode="orderCode"
        :businessType="businessType"
        :proId="processId"
        :optionType="optionType"
        :editData="editData"
        :comps="compts"
        @remind="remind"
      ></process-order>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="small"
          >取 消</el-button
        >
        <el-button
          v-if="optionType != 0"
          @click="preserveHandler(0)"
          size="small"
          >保 存</el-button
        >
        <el-button
          v-if="optionType != 0"
          type="primary"
          @click="preserveHandler(1)"
          size="small"
          >提 交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getAllUserInfo } from "@/api/base";
import {
  getTypetree,
  getProcessPageList,
  queryProcessPage,
  getProcessList2,
  qOrderProcessById,
  addOrderProcess,
  delOrderProcess,
  querySupervisePage,
} from "@/api/process/process";
import { config } from "../../../components/cfgOrderProcess";
import processOrder from "@/views/mbsys/publicOrder/orderProcess/detail";
import { publicComponents } from "../processForm/config";
export default {
  components: { processOrder },
  data() {
    return {
      // form
      config: config,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      allDept: [], //所有部门
      curUser: null, //当前登录人
      orderName: "会议申请单", //工单名称
      orderCode: "", //工单编号
      form: {
        content: "", //关键字
        supplierId: "", //供应商
      },
      tableData: [],
      title: "",
      pagination: { current: 1, size: 20, total: 0 },
      dialogFormVisible: false,
      curProcess: null,
      businessType: 0, //业务类型
      optionType: 0, //操作类型 0:查看,1:新增,2:修改
      editData: {}, //操作数据
      processId: 0, //流程ID
      compts: publicComponents,
      curEditRow: null, //当前操作数据
    };
  },
  watch: {},
  created() {
    this.curUser = this.$store.state.user;
    //获取业务类别
    getTypetree({ datatypes: 0, id: "" })
      .then((res) => {
        if (res.code === 1) {
          if (res.result.length > 0)
            if (res.result[0].vos.length > 1)
              this.businessTypes = res.result[0].vos[0].vos;
        }
      })
      .catch((ex) => {
        this.$message.error("获取数据出错!");
      });
    /**
     * 查询所有用户所有部门和所有人
     */
    getAllUserInfo().then((res) => {
      if (res.code == 1) {
        const data = res.result;
        for (const i in data) {
          data[i].value = data[i].id;
          data[i].label = data[i].name;
          if (data[i].users) {
            data[i].children = data[i].users;
            for (const j in data[i].children) {
              data[i].children[j].value = data[i].children[j].id;
              data[i].children[j].label = data[i].children[j].realName;
            }
          }
        }
        this.allDept = data;
      }
    });
    this.getProcess();
  },
  methods: {
    /**
     * 根据部门ID获取部门名称
     */
    getDeptName(deptId) {
      if (this.allDept.length > 0) {
        const dept = this.allDept.find((item) => item.id == deptId);
        if (dept) return dept.name;
        else deptId;
      } else return deptId;
    },
    /**
     * 根据部门ID和人员id获取人员名称
     */
    getUserName(deptId, userId) {
      if (this.allDept.length > 0) {
        const dept = this.allDept.find((item) => item.id == deptId);
        if (dept) {
          const user = dept.users.find((p) => p.id == userId);
          if (user) return user.realName;
          else return userId;
        } else return userId;
      } else return userId;
    },
    changePaginationSize(value) {
      this.pagination.size = value;
      this.queryProcess();
    },

    changePaginationCurrent(value) {
      this.pagination.current = value;
      this.queryProcess();
    },

    /**
     * 获取催办消息
     */
    async getUrgeInfo(data) {
      // this.tableData.forEach((row) => {

      // });
      let tableList = data;
      for (let i = 0; i < tableList.length; i++) {
        tableList[i]["urgeInfo"] = "";
        if (tableList[i].urgeNumber > 0) {
          let data = {
            processId: tableList[i].id, //流程ID
            nodeBranch: tableList[i].nodeBranch, //流程节点分支
            processNode: tableList[i].processNode, //流程节点
            superviseDept: parseInt(this.curUser.departmentId), //督办部门
            superviseStaff: this.curUser.userId, //督办人
          };
          const res = await this.querySupervisePage(data);

          let result = [];
          if (res) {
            res.result.records.forEach((item) => {
              const dept = this.getDeptName(item.handleDept);
              result.push(
                item.createTime +
                  " " +
                  dept +
                  " " +
                  item.createUserName +
                  " " +
                  item.remark
              );
            });
          }

          tableList[i]["urgeInfo"] = result;
        }
      }
      this.tableData = tableList;
    },

    /**
     * 查询工单列表
     */
    queryProcess() {
      //带入当前登录人查询
      //ywType 业务类型,基础类型
      //configId 流程类型
      //registerStaff 登记人
      //processState 工单状态:1草稿、2处理、3终止、4处理完成
      let map = {
        // processType: 94,
        configId: this.processId,
        registerStaff: Number(this.curUser.userId),
      };
      let params = {
        id: 3,
        map,
      };
      let { current, size, total } = this.pagination;
      let url = `current=${current}&size=${size}&total=${total}`;

      if (this.form.content != "")
        Object.assign(map, { content: this.form.content });
      if (this.form.registerDept != "")
        Object.assign(map, { registerDept: this.form.registerDept });
      if (this.form.purchaseTime) {
        Object.assign(map, {
          stratTime: this.form.purchaseTime[0] + " 00:00:00",
          endTime: this.form.purchaseTime[1] + " 23:59:59",
        });
      }
      getProcessList2(params, url).then((res) => {
        if (res.code == 1) {
          //this.tableData = res.result.records;
          this.getUrgeInfo(res.result.records);
          this.pagination.total = res.result.total;
        }
      });
    },

    /**
     * 查询列表数据
     */
    getProcess() {
      let data = {
        current: 1,
        size: 999,
      };
      getProcessPageList(data)
        .then((res) => {
          this.curProcess = res.result.records.find(
            (item) => item.processNumber === "HYLC"
          );
          if (this.curProcess) {
            this.processId = this.curProcess.id;
            this.businessType = this.curProcess.hasOwnProperty("processType")
              ? this.curProcess.processType
              : null;
          }
          this.queryProcess();
        })
        .catch((ex) => {
          this.$message.error("获取流程列表失败!");
        });
    },

    // 提示
    remind(data) {
      this.dialogFormVisible = false;
      //设置初始操作类型
      this.optionType = 1;
      this.queryProcess();
    },

    orderRegister() {
      this.title = "会议申请-新增";
      this.optionType = 1; //操作类型 0:查看,1:新增,2:修改
      this.editData = {};
      this.curEditRow = null;
      this.dialogFormVisible = true;
    },
    /**
     * 根据id获取工单状态
     */
    getOrderStateNameById(id) {
      if (this.config && this.config.hasOwnProperty("orderState")) {
        const obj = this.config.orderState.find((item) => item.key === id);
        if (obj) return obj.value;
        else return id;
      } else {
        return id;
      }
    },
    /**
     * 通过id查询工单流程信息
     * @row 查询数据
     * @type 操作类型 false:查看,true:修改
     */
    queryOrderProcessById(row, type) {
      this.curEditRow = type ? row : null;
      qOrderProcessById(row.id).then((res) => {
        if (res.code == 1) {
          this.title = type ? "会议申请-修改" : "会议申请-详情";
          this.optionType = type ? 2 : 0;
          this.editData = res.result;
          this.dialogFormVisible = true;
        }
      });
    },

    /**
     * 删除工单流程
     */
    delOrderProcessById(row) {
      this.$confirm(
        `此操作将永久删除单号为【${row.processNumber}】名称为【${row.name}】的单, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.deleteOrder(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /***
     * 删除工单流程
     */
    deleteOrder(id) {
      delOrderProcess(id).then((res) => {
        if (res.code == 1) {
          this.queryProcess();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        } else {
          this.$message({
            type: "error",
            message: "删除失败",
          });
        }
      });
    },
    /**
     * 新增工单流程信息
     */
    addOrder(param) {
      addOrderProcess(param).then((res) => {
        if (res.code == 1) {
          this.dialogFormVisible = false;
          this.queryProcess();
          this.$message.success("编辑成功!");
        }
      });
    },

    /**
     * 提交数据
     * @state 操作状态  保存为0,提交为1
     */
    preserveHandler(state) {
      let params = this.$refs.merge.submitForm();
      console.log("提交数据", params);
      if (params == null) return;
      //处理提交参数到接口参数映射
      let data = this.formParamMapping(params, state);
      if (data) this.addOrder(data);
    },

    /**
     * 表单参数映射到提交参数
     */
    formParamMapping(data, state) {
      let params = {
        operateState: 0, //	表单类型:0、其它; 1、采购入库(关联采购工单);2、余料退库(关联出库工单);3、工程出库(关联工程工单);4其它出库;5、维修出库(关联维修工单)
      };
      let formData = new FormData();
      if (this.curEditRow != null)
        Object.assign(params, { id: this.curEditRow.id }); //流程ID
      //表单字段
      if (data.hasOwnProperty("configId")) {
        params = Object.assign(params, { configId: data.configId }); //流程配置ID
      }
      let documentDto = {
        content: data.form.content, //会议内容
        theme: data.form.name, //主题
      };
      // 关联设施字段
      let prdtos = [];
      prdtos.push({
        relationId: data.form.relationId, //会议地址
        tableId: 1, //会议地址
      });
      let processNode = {
        //第一步
        handleResults: 0, //处理结果0:不处理;1:同意;2:不同意;
        saveState: state, //0保存,1提交
        annex: data.hasOwnProperty("existsFilesId") ? data.existsFilesId : "", //附件id
        remark: data.hasOwnProperty("examine") ? data.examine.remarks : "",
        typeOne: data.form.typeOne, //是否发送通知
        documentDto,
        prdtos,
        staffDtos: data.form.staffDtos,
      };
      if (data.hasOwnProperty("form")) {
        Object.assign(params, {
          name: data.form.name, //	表单名称
          registerTime: data.form.registerTime, //登记时间
          startTime:
            data.form.startTime.length > 11
              ? data.form.startTime
              : data.form.startTime + " 00:00:00", // 时间
          endTime:
            data.form.endTime.length > 11
              ? data.form.endTime
              : data.form.endTime + " 00:00:00", // 时间
          remark: data.form.remark, //备注
          totalPrice: data.form.totalPrice, // 人数
        });
      }
      Object.assign(params, { ywType: this.businessType }); //业务类型
      //审核信息
      if (data.hasOwnProperty("examine")) {
        //下一步审核
        let nextStep = {
          dept: data.examine.hasOwnProperty("dept") ? data.examine.dept : "", //部门
          deptStaff: data.examine.hasOwnProperty("deptStaff")
            ? data.examine.deptStaff
            : "", //人员
          processStep: data.examine.hasOwnProperty("processStep")
            ? data.examine.processStep
            : 1, //流程步骤
          stepNode: data.examine.hasOwnProperty("stepNode")
            ? data.examine.stepNode
            : 1, //步骤节点
        };

        Object.assign(processNode, {
          headleState: data.examine.headleState, //处理状态:1提交;2:驳回;3:转派;4:终止;
          nextStep: nextStep, //下一步信息,下一步,驳回,转派
          processStep: 1, //流程步骤(当前)
          stepNode: 1, //步骤节点(当前)
        });
        if (
          state == 1 &&
          data.examine.headleState == 1 &&
          (nextStep.deptStaff == "" || nextStep.deptStaff == null)
        ) {
          this.$message.warning("提交请选择下一步审核人");
          return null;
        }
      }
      //	步骤节点 stepNode
      Object.assign(params, { stepNode: 1 });

      Object.assign(params, { processNode: processNode }); //业务类型
      const json = JSON.stringify(params);
      // 将 json 字符串转化为 Blob 对象
      const blob = new Blob([json], {
        type: "application/json",
      });
      formData.append("dto", blob);
      //文件
      if (data.hasOwnProperty("files")) {
        let files = [];
        data.files.forEach((file, index) => {
          formData.append("fileList", file.file);
        });
      }
      return formData;
    },
    // 详细
    newPlanForMonthDia(bool, e) {},
    // 新增页面确定按钮
    applicationFn() {
      if (!this.sizeForm.name) return this.$message.error("请输入会议名称");
      if (!this.sizeForm.address) return this.$message.error("请输入地点");
      if (!this.sizeForm.startDate)
        return this.$message.error("请输入会议时间");
      if (!this.sizeForm.people) return this.$message.error("请输入参会人员");
      if (!this.sizeForm.department)
        return this.$message.error("请输入申请部门");
      if (!this.sizeForm.name2) return this.$message.error("请输入申请人");
      if (!this.sizeForm.value1) return this.$message.error("请输入申请时间");
    },
  },
};
</script>
<style lang="scss" scoped>
.content-container {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  position: absolute;
  top: 43px;
  bottom: 0;

  .right-box {
    height: 100%;
    overflow-y: auto;
    box-sizing: border-box;

    .top {
      height: 33px;
      text-align: right;

      .upload-demo {
        display: inline-block;
      }
    }
    // /deep/.el-form-item__content {
    //   display: flex;
    //   align-items: center;
    // }

    .table-div {
      height: calc(100% - 81px);
    }

    .el-pagination {
      margin-top: 16px;
    }
  }
}
.el-table {
  >>> .el-table__body {
    tr {
      &:nth-child(2n) {
        background-color: #f0f9eb;
      }
      td {
        height: 23px;
        line-height: 23px;
        padding: 2px 1px !important;
        .el-button {
          padding: 0;
        }
      }
    }
  }
}

.tf-dialog {
  >>> .el-dialog__header {
    background: #2d74e7;
    .el-dialog__title {
      color: aliceblue !important;
    }
    .el-dialog__close {
      color: aliceblue !important;
    }
  }
}
</style>