<template>
  <div class="container_main">
    <div class="sidebar_btn">
      <el-button
        class="flex"
        @click="sendValue"
        size="medium"
        icon="el-icon-back"
        type="primary"
        plain
        >返回</el-button
      >
      <p>隐患检查字段设置</p>
    </div>
    <div class="sidebar_content">
      <div class="content-header">
        <div>
          <div>检查类别</div>
          <el-radio-group
            @change="onRecordChange"
            v-model="recordType"
            size="medium"
          >
            <el-radio-button :label="1">安全管理</el-radio-button>
            <el-radio-button :label="2">排查记录</el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <div>
            是否启用项目端配置
            <el-tooltip
              class="item"
              effect="dark"
              content="Bottom Center 提示文字"
              placement="bottom"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>

            <el-switch
              @change="saveConfigSecurityDangerFieldConfig"
              :value="enableProject"
            >
            </el-switch>
          </div>
          <el-button @click="saveConfigClick" type="primary" size="medium"
            >保存配置</el-button
          >
        </div>
      </div>
      <el-table
        ref="tableRef"
        class="tables"
        row-key="id"
        :data="tableData"
        :row-class-name="getRowClass"
      >
        <el-table-column
          prop="originalFieldName"
          align="center"
          label="初始字段名"
        />
        <el-table-column
          prop="displayFieldName"
          align="center"
          label="显示字段名"
        >
          <template slot-scope="scope">
            <el-input
              :disabled="!enableProject"
              v-model="scope.row.displayFieldName"
              placeholder="请输入"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="defaultDataType" align="center" label="默认数据">
          <template slot-scope="scope">
            <el-select
              :disabled="!enableProject"
              v-model="scope.row.defaultDataType"
              placeholder="请选择"
            >
              <el-option
                :label="item.title"
                :value="item.id"
                v-for="item in scope.row.defaultDataTypeList"
                :key="item.id"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="isRequired" align="center" label="是否必填">
          <template slot-scope="scope">
            <el-switch
              :disabled="!enableProject"
              v-model="scope.row.isRequired"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="isEnabled" align="center" label="是否启用">
          <template slot-scope="scope">
            <el-switch
              :disabled="!enableProject"
              v-model="scope.row.isEnabled"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="isPinned" align="center" label="是否固定到列表">
          <template slot-scope="scope">
            <el-switch
              :disabled="!enableProject"
              v-model="scope.row.isPinned"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div class="icon-movement_box" v-if="enableProject">
              <div class="icon-movement"></div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import {
  getEffectiveConfigSecurityDangerFieldApi,
  saveAllSecurityDangerFieldApi,
  getSecurityDangerFieldConfigListApi,
  saveConfigSecurityDangerFieldConfigApi,
} from "@/assets/js/api/safeManage";
import { getDictionaryItemApi } from "@/assets/js/api/companyDiagram";
import Sortable from "sortablejs";
export default {
  name: "hiddenDangerSet",
  data() {
    return {
      pageInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0, //总条数
      },
      projectSn: "",
      radio2: 1,
      tableData: [],
      dragState: {
        isDragging: false,
        dragIndex: -1,
        newDragIndex: -1,
      },
      dangerItemList: [],
      recordType: 1,
      enableProject: false,
    };
  },
  created() {
    this.projectSn = this.$store.state.projectSn;
    this.getDicProjectTypeList();
    this.onRecordChange();
  },
  mounted() {
    this.initSortable();
  },
  methods: {
    saveConfigClick() {
      const resultList = this.tableData.map((item) => {
        return {
          ...item,
          sn: this.projectSn,
          isRequired: item.isRequired ? 1 : 0,
          isEnabled: item.isEnabled ? 1 : 0,
          isPinned: item.isPinned ? 1 : 0,
        };
      });
      let params = {
        fieldList: resultList,
        sn: this.projectSn,
        companyProjectType: 1,
        recordType: this.recordType,
      };
      saveAllSecurityDangerFieldApi(params).then((res) => {
        console.log(res);
        if (res.code && res.success) {
          // '保存成功！'
          this.$message.success(this.$t("message.highModulus.saveSuccessMsg"));
          this.getSecurityDangerFieldPage();
        }
      });
    },
    saveConfigSecurityDangerFieldConfig(event) {
      console.log(event);
      this.$confirm("确定启用项目端配置吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        saveConfigSecurityDangerFieldConfigApi({
          projectSn: this.projectSn,
          recordType: this.recordType,
          enableProject: event ? 1 : 0,
        }).then((res) => {
          console.log(res);
          if (res.code && res.success) {
            this.$message.success("配置成功!");
            this.getSecurityDangerFieldConfigList();
          }
        });
      });
    },
    onRecordChange() {
      this.enableProject = false;
      this.getSecurityDangerFieldPage();
      this.getSecurityDangerFieldConfigList();
    },
    getSecurityDangerFieldPage() {
      getEffectiveConfigSecurityDangerFieldApi({
        pageNo: 1,
        pageSize: -1,
        sn: this.projectSn,
        companyProjectType: 2,
        recordType: this.recordType,
      }).then((res) => {
        if (res.code === 200) {
          let objListName = [];
          if (this.recordType == 1) {
            objListName = [
              {
                key: "regionIds",
                value: "责任区域",
              },
              {
                key: "detailPlace",
                value: "详细部位",
              },
              {
                key: "dangerItemId",
                value: "问题描述",
              },
              {
                key: "dangerItemId",
                value: "问题分类",
              },
              {
                key: "dangerDesc",
                value: "补充说明",
              },
              {
                key: "remark",
                value: "整改要求",
              },
              {
                key: "addedDescription",
                value: "事件描述",
              },
              {
                key: "level",
                value: "问题等级",
              },
              {
                key: "priorityNameDic",
                value: "问题等级二",
              },
              {
                key: "urgentLevel",
                value: "紧急程度",
              },
              {
                key: "inspectTime",
                value: "检查时间",
              },
              {
                key: "enterpriseIds",
                value: "分包单位",
              },
              {
                key: "changeLimitTime",
                value: "整改时限",
              },
              {
                key: "changeId",
                value: "整改人",
              },
              {
                key: "reviewIds",
                value: "复查人",
              },
              {
                key: "verifyManIds",
                value: "核验人",
              },
              {
                key: "imageUrl",
                value: "隐患图片",
              },
              {
                key: "fileUrl",
                value: "上传附件",
              },
              {
                key: "status",
                value: "现场整改",
              },
              {
                key: "rectifyAfterImage",
                value: "整改后图片",
              },
              {
                key: "dutyMajor",
                value: "责任专业",
              },
            ];
          } else if (this.recordType == 2) {
            objListName = [
              {
                key: "regionIds",
                value: "检查部位",
              },
              {
                key: "dangerItemId",
                value: "排查分类",
              },
              {
                key: "addedDescription",
                value: "事件描述",
              },
              {
                key: "dangerDesc",
                value: "补充说明",
              },
              {
                key: "inspectTime",
                value: "检查时间",
              },
              {
                key: "enterpriseIds",
                value: "分包单位",
              },
              {
                key: "imageUrl",
                value: "上传图片",
              },
              {
                key: "fileUrl",
                value: "上传附件",
              },
            ];
          }

          const resultList = objListName.map((item, index) => {
            return {
              //   id: 'id-' + Math.random().toString(36).substr(2, 9),
              sort: index,
              fieldType: 0,
              originalFieldName: item.value,
              fieldName: item.key,
              displayFieldName: "",
              defaultDataType: "",
              isRequired: true,
              isEnabled: true,
              isPinned: true,
              defaultDataTypeList: this.defaultDataFn(item.value),
            };
          });
          const dataList =
            res.result.length > 0
              ? res.result.map((item) => {
                  return {
                    ...item,
                    defaultDataTypeList: this.defaultDataFn(
                      item.originalFieldName
                    ),
                    isRequired: item.isRequired === 1,
                    isEnabled: item.isEnabled === 1,
                    isPinned: item.isPinned === 1,
                    defaultDataType: item.defaultDataType
                      ? item.defaultDataType
                      : "",
                  };
                })
              : resultList;
          this.tableData = dataList.sort((a, b) => a.sort - b.sort);
        }
      });
    },
    getSecurityDangerFieldConfigList() {
      getSecurityDangerFieldConfigListApi({
        projectSn: this.projectSn,
        recordType: this.recordType,
      }).then((res) => {
        if (res.code == 200) {
          console.log(res.result);
          if (res.result.length > 0) {
            this.enableProject =
              res.result[0].enableProject == 1 ? true : false;
          }
        }
      });
    },
    defaultDataFn(typeName) {
      let resultList = [];
      if (["责任区域", "检查部位"].includes(typeName)) {
        resultList = [
          {
            id: 1,
            title: "所有部位",
          },
        ];
      } else if (["问题等级"].includes(typeName)) {
        resultList = ["一级", "二级", "三级", "四级"].map((item, index) => {
          return {
            id: index + 1,
            title: item,
          };
        });
      } else if (["问题等级二"].includes(typeName)) {
        resultList = this.dangerItemList.map((item, index) => {
          return {
            id: Number(item.data),
            title: item.name,
          };
        });
      } else if (["紧急程度"].includes(typeName)) {
        resultList = ["一般", "严重", "紧要"].map((item, index) => {
          return {
            id: index + 1,
            title: item,
          };
        });
      } else if (["检查时间"].includes(typeName)) {
        resultList = [
          {
            id: 1,
            title: "系统当前时间",
          },
        ];
      } else if (["分包单位"].includes(typeName)) {
        resultList = [
          {
            id: 1,
            title: "所有区域绑定的责任单位",
          },
        ];
      } else if (["整改时限"].includes(typeName)) {
        resultList = [
          {
            id: 1,
            title: "按隐患库设置的时限",
          },
        ];
      } else if (["整改人"].includes(typeName)) {
        // resultList = [
        //   {
        //     id: 1,
        //     title: "所有区域绑定的整改人",
        //   },
        // ];
      } else if (["复查人"].includes(typeName)) {
        resultList = [
          {
            id: 1,
            title: "所有区域绑定的复查人",
          },
        ];
      } else if (["核验人"].includes(typeName)) {
        resultList = [
          {
            id: 1,
            title: "检查人作为核验人",
          },
        ];
      } else if (["现场整改"].includes(typeName)) {
        return ["未整改", "已整改"].map((item, index) => {
          return {
            id: index == 0 ? "" : 5,
            title: item,
          };
        });
      }
      return [
        ...resultList,
        {
          id: "",
          title: "无",
        },
      ];
    },
    // 获取字典工程类别列表
    getDicProjectTypeList() {
      getDictionaryItemApi({
        dictionaryEncoding: "xz_security_danger_item_record_priority_name_dic",
        projectSn: this.projectSn,
      }).then((res) => {
        if (res.result.length > 0) {
          this.dangerItemList = res.result;
        }
      });
    },
    initSortable() {
      // 在 mounted 生命周期获取表格 tbody 元素
      this.$nextTick(() => {
        const tbody = this.$refs.tableRef.$el.querySelector(
          ".el-table__body tbody"
        );
        if (tbody) {
          new Sortable(tbody, {
            animation: 150, // 动画时长
            handle: ".icon-movement", // 拖拽触发元素
            onEnd: (evt) => {
              //   const data = this.tableData[evt.oldIndex];
              const dataList = this.tableData.map((item, index) => {
                if (index > evt.oldIndex && index <= evt.newIndex) {
                  item.sort = item.sort - 1;
                } else if (evt.oldIndex == index) {
                  item.sort = evt.newIndex;
                }
                return item;
              });
              this.tableData = dataList.sort((a, b) => a.sort - b.sort);
              //   this.tableData.splice(evt.oldIndex, 1);
              //   this.tableData.splice(evt.newIndex, 0, data);
            },
          });
        }
      });
    },
    getRowClass({ row, rowIndex }) {
      //   if (rowIndex === this.dragState.newDragIndex) {
      //     return "isDragBox active-drag drag-over";
      //   }
      //   if (rowIndex === this.dragState.dragIndex) return "isDragBox dragging";
      //   return "isDragBox";
    },
    sendValue() {
      // 返回逻辑
      this.$emit("updateValue", 0);
    },
  },
};
</script>
<style lang="less" scoped>
.isDragBox {
  cursor: move;
  position: relative;
}
.active-drag {
  position: relative;
  &::after {
    content: "";
    position: absolute;
    top: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #4b79f3;
    z-index: 99;
  }
}
/deep/ .el-table__body-wrapper {
  .el-table__row {
    transition: all 0.2s;
    &.dragging {
      opacity: 0.5;
      background: #f0f0f0;
    }
    &.drag-over {
      border-top: 2px solid #1890ff;
      background: #e6f7ff;
    }
  }
}
.icon-movement_box {
  width: 100%;
  display: flex;
  justify-content: center;
}
.icon-movement {
  cursor: grab;
  width: 20px;
  height: 20px;
  background-image: url("~@/assets/images/icon-movement.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.sidebar_content {
  padding: 15px;
  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    > div:last-child {
      display: flex;
      align-items: center;
      > div:first-child {
        display: flex;
        align-items: center;
        .el-switch {
          margin: 0 15px;
        }
      }
    }
    > div:first-child {
      display: flex;
      align-items: center;
      > div:first-child {
        margin-right: 16px;
      }
    }
  }
}
.flex {
  display: flex;
}
:deep(.el-icon-back) {
  background-image: url("~@/assets/images/rollback-icon.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  width: 14px;
  height: 14px;
  background-color: white;
  border-radius: 50%;
}
:deep(.el-icon-back::before) {
  display: none;
}
.sidebar_btn {
  padding: 15px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  //   justify-content: space-between;
  align-items: center;
  .el-button + .el-button,
  p {
    margin-left: 8px;
  }
}
.container_main {
  width: calc(100%);
  height: calc(100%);
  overflow-y: auto;
  overflow-x: hidden;
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
