<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="安全措施模板名称：">
          <el-input
            v-model="search.workTicketOptionName"
            placeholder="请输入安全措施模板名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="作业票类型：">
          <el-select v-model="search.workTicketType" size="medium" clearable>
            <el-option
              v-for="item in ticketType"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <div class="headerTop">
        <div>
          <el-button
            type="primary"
            class="el-icon-plus"
            @click="handleItem('add')"
          >
            新增</el-button
          >
          <el-button
            icon="el-icon-delete"
            type="primary"
            :disabled="multipleSelection.length < 1"
            @click="dleSignTemolate"
            >删除</el-button
          >
          <!-- <el-button
            type="primary"
            class="el-icon-download"
            @click="handleExport"
          >
            导出文档</el-button
          > -->
        </div>
        <right-toolbar
          :showSearch.sync="isSearch"
          @queryTable="reset"
        ></right-toolbar>
      </div>
      <el-table
        height="calc(100% - 200px)"
        :data="list"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" width="50px" />
        <el-table-column label="序号" align="center" width="80px">
          <template slot-scope="scope">
            <span> {{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="安全措施模板名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.workTicketOptionName || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="作业票类型" align="center">
          <template slot-scope="scope">
            <span>{{ workTicketType[scope.row.workTicketType] || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="作业票级别" align="center">
          <template slot-scope="scope">
            <span>{{ levelType[scope.row.workTicketLevel] || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleItem('edit', scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleItem('check', scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="dleSignTemolate(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="getList"
      />
    </el-main>
    <el-dialog
      :visible.sync="addAlert"
      width="60%"
      :title="title"
      :show-close="false"
    >
      <el-form
        ref="formData"
        :model="formData"
        label-position="right"
        :rules="rules1"
        style="padding: 0 20px; height: 700px; overflow: auto"
        :disabled="isCheck"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label-width="150px"
              label="模板名称："
              prop="workTicketOptionName"
            >
              <el-input
                style="width: 90%"
                v-model="formData.workTicketOptionName"
                placeholder="请输入名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label-width="150px"
              label="作业票类型："
              prop="workTicketType"
            >
              <el-select
                style="width: 90%"
                v-model="formData.workTicketType"
                size="medium"
                clearable
              >
                <el-option
                  v-for="item in ticketType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="['10', '40', '50'].includes(formData.workTicketType)">
          <el-col :span="12">
            <el-form-item
              label-width="150px"
              label="作业票级别："
              prop="workTicketLevel"
            >
              <el-select
                style="width: 90%"
                v-model="formData.workTicketLevel"
                size="medium"
              >
                <el-option
                  v-for="item in level"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label-width="150px" label="安全措施项列表：">
          <div
            v-for="(edit, index) in formData.workTicketSmOptionDTOList"
            :key="index"
            class="form-list"
          >
            <div class="form-item">
              <el-form-item
                label-width="60px"
                :label="index + 1 + '、'"
                :prop="homeCheck(index)"
                :rules="[
                  {
                    required: true,
                    message: '请输入安全措施项',
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  v-model="edit.workTicketSmOption"
                  placeholder="请输入内容"
                  type="textarea"
                  :rows="3"
                />
              </el-form-item>
            </div>
            <div class="add_button" v-if="!isCheck">
              <span
                v-if="formData.workTicketSmOptionDTOList.length !== 1"
                @click="handleDelItmes(index)"
                class="el-icon-remove"
              />
              <span
                v-if="formData.workTicketSmOptionDTOList.length === index + 1"
                class="el-icon-circle-plus"
                @click="addItem"
              />
            </div>
            <div v-else style="width: 26px"></div>
          </div>
        </el-form-item>
      </el-form>
      <el-row style="margin-top: 10px">
        <el-col align="right">
          <el-button @click="handleClose"> 取消 </el-button>
          <el-button
            :loading="loading"
            type="primary"
            @click="handleSave"
            v-if="!isCheck"
          >
            确定
          </el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </el-container>
</template>

<script>
import {
  measuresList,
  delMeasures,
  addMeasuresTemplate,
  editMeasuresTemplate,
  dictType,
  listUser,
  listPost,
  getMeasuresDetails,
} from "@/api/jobSheet.js";
export default {
  name: "RuoyiIndex",

  data() {
    return {
      loading: false,
      //模糊搜索
      search: {
        workTicketOptionName: "",
        workTicketType: "",
      },
      title: "",
      type: "",
      total: 0,
      isSearch: true,
      list: [],
      multipleSelection: [],
      pageNum: 1,
      pageSize: 10,
      addAlert: false,
      isCheck: false,
      rowId: "",
      formData: {
        workTicketLevel: "",
        workTicketSmOptionDTOList: [
          {
            workTicketSmOption: "",
          },
        ],
        workTicketOptionName: "",
        workTicketType: "",
      },
      rules1: {
        workTicketOptionName: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
        ],
        workTicketType: [
          { required: true, message: "请选择类型", trigger: "blur" },
        ],
        workTicketLevel: [
          { required: true, message: "请选择级别", trigger: "blur" },
        ],
      },
      level: [
        {
          code: "10",
          name: "特级",
        },
        {
          code: "20",
          name: "一级",
        },
        {
          code: "30",
          name: "二级",
        },
      ],
      ticketType: [],
      userList: [],
      postList: [],
      signType: [
        {
          code: "10",
          name: "人员",
        },
        {
          code: "20",
          name: "岗位",
        },
      ],
    };
  },
  computed: {
    workTicketType() {
      return this.ticketType.reduce((t, item) => {
        return {
          ...t,
          [item.dictValue]: item.dictLabel,
        };
      }, {});
    },
    levelType() {
      return this.level.reduce((t, item) => {
        return {
          ...t,
          [item.code]: item.name,
        };
      }, {});
    },
    homeCheck() {
      return (index) => `workTicketSmOptionDTOList.${index}.workTicketSmOption`;
    },
  },
  created() {
    this.getTotalList();
  },
  mounted() {
    this.getList();
  },

  methods: {
    reset() {
      this.search = this.$options.data().search;
      this.getList();
    },
    getTotalList() {
      const params = {
        pageNum: 1,
        pageSize: 100,
      };
      dictType({ ...params, dictType: "sys_work_ticket_type" }).then((data) => {
        if (data.code === 200) {
          this.ticketType = data.rows;
        } else {
          this.$message.error(data.msg);
        }
      });
      listUser(params).then((data) => {
        if (data.code === 200) {
          this.userList = data.rows;
        } else {
          this.$message.error(data.msg);
        }
      });
      listPost(params).then((data) => {
        if (data.code === 200) {
          this.postList = data.rows;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    handleSign(index) {
      this.formData.workTicketSmOptionDTOList[index].workTicketSignUserIdList =
        [];
    },
    getList() {
      const params = {
        ...this.search,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      measuresList(params).then((data) => {
        if (data.code === 200) {
          this.list = data.rows;
          this.total = data.total;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 全选/反选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    dleSignTemolate(row) {
      let ids =
        row.id || this.multipleSelection.map((item) => item.id).join(",");
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delMeasures(ids).then((data) => {
            if (data.code === 200) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          // 取消后退出
        });
    },
    // 取消添加
    handleClose() {
      this.addAlert = false;
      setTimeout(() => {
        this.isCheck = false;
        this.formData = this.$options.data().formData;
        this.$refs.formData.resetFields();
      }, 200);
    },
    handleDelItmes(index) {
      this.$confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.formData.workTicketSmOptionDTOList.splice(index, 1);
        })
        .catch(() => {
          // 取消后退出
        });
    },
    addItem() {
      this.formData.workTicketSmOptionDTOList.push({
        workTicketSmOption: "",
      });
    },
    handleSave() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.type === "add") {
            addMeasuresTemplate(this.formData)
              .then((data) => {
                if (data.code === 200) {
                  this.$message({
                    message: "新增成功",
                    type: "success",
                  });
                  this.handleClose();
                  this.getList();
                } else {
                  this.$message.error(data.msg);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            editMeasuresTemplate({ ...this.formData, id: this.rowId })
              .then((data) => {
                if (data.code === 200) {
                  this.$message({
                    message: "编辑成功",
                    type: "success",
                  });
                  this.handleClose();
                  this.getList();
                } else {
                  this.$message.error(data.msg);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    getDetails(id) {
      getMeasuresDetails(id).then((data) => {
        if (data.code === 200) {
          this.formData = data.data;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    handleItem(type, row = {}) {
      this.addAlert = true;
      this.type = type;
      this.rowId = row.id;
      if (type === "add") {
        this.title = "新增";
      } else if (type === "edit") {
        this.title = "编辑";
        this.getDetails(row.id);
      } else if (type === "check") {
        this.title = "查看";
        this.isCheck = true;
        this.getDetails(row.id);
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/worktecket/sign/template/export",
        {},
        `job_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.form-list {
  display: flex;
  .form-item {
    flex: 1;
    margin-bottom: 20px;
  }
  .add_button {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin-left: 10px;
    margin-bottom: 20px;
    .el-icon-circle-plus {
      font-size: 26px;
      color: #67c23a;
      cursor: pointer;
    }
    .el-icon-remove {
      font-size: 26px;
      color: #f56c6c;
      cursor: pointer;
    }
  }
}
</style>
