<template>
  <div>
    <!-- 标题部分 -->
    <el-row>
      <el-col :span="24" class="first-row">
        <div class="tag">重点人员</div>
      </el-col>
    </el-row>

    <!-- 分割线 -->
    <div style="margin: 18px 0"></div>
    <hr style="background-color: #cccccc; height: 1px; border: 0" />

    <!-- 主体内容部分 -->

    <!-- 时间选择框区域 -->
    <el-row>
      <el-form :inline="true" style="padding-top: 13px">
        <el-form-item label="起止时间：">
          <el-date-picker
            v-model="select_datetime"
            type="daterange"
            align="center"
            unlink-panels
            range-separator="至"
            :start-placeholder="startTime"
            :end-placeholder="endTime"
            @change="dateChange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            class="shijian_plus"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处置情况：">
          <el-select v-model="people_state" @change="stateChange">
            <el-option
              v-for="item in state_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询：" style="marginleft: -30px">
          <el-input
            suffix-icon="el-icon-search"
            placeholder="请输入姓名"
            clearable
            v-model="keyWord"
            @change="handleSearch"
            @clear="handleClear"
          ></el-input>
        </el-form-item>
        <el-form-item style="marginleft: 10px">
          <el-button size="mini" type="success" @click="exportServerExcel">
            后台数据导出
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="exportExcel('起止时间')"
          >
            当前列表导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 分割线 -->
    <hr style="background-color: #cccccc; height: 1px; border: 0" />

    <!-- 表单部分 -->
    <el-row>
      <el-table
        :data="tableData"
        ref="tableList"
        id="exportTab"
        border
        highlight-current-row
        v-loading="loading"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
        height="500"
      >
        <el-table-column prop="sm_name" label="姓名" align="center" width="70">
        </el-table-column>
        <el-table-column
          prop="sm_phone"
          label="联系方式"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="sm_card"
          label="身份证"
          align="center"
          width="170"
        >
        </el-table-column>
        <el-table-column prop="sm_color" label="码色" align="center" width="70">
        </el-table-column>
        <el-table-column prop="leixing" label="人员类型" align="center">
        </el-table-column>
        <el-table-column prop="sm_time" label="时间" align="center" width="100">
        </el-table-column>
        <el-table-column
          prop="handler_unit"
          label="处理单位"
          align="center"
          width="130"
        >
        </el-table-column>
        <el-table-column label="轨迹" align="center" show-overflow-tooltip>
          <template slot-scope="{ row }">
            {{ row.jingwei_place + "->" + row.trace_after }}
          </template>
        </el-table-column>
        <el-table-column label="处理情况" width="120" align="center">
          <template slot-scope="scope">
            <div
              v-if="
                scope.row.handler_state2 === '0' ||
                scope.row.handler_message === '待处置'
              "
            >
              <el-select
                v-if="myArr"
                style="width: 100%"
                size="mini"
                v-model="myArr[scope.$index].label"
                placeholder="待处理"
                @change="handleShowDialog(scope.$index, scope.row)"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </div>
            <div v-else>{{ scope.row.handler_message }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="处置详情"
          align="center"
          prop="message_commit"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="{ row }">
            <el-button
              :disabled="row.handler_state2 === '0'"
              type="text"
              size="mini"
              style="width: 60px"
              @click="handleThemeModifyClick(row)"
              >编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              style="width: 60px"
              @click="guiXiang(row)"
              >轨迹详情
            </el-button>
            <el-button
              type="text"
              size="mini"
              style="width: 60px"
              @click="deleteTitle(row)"
              >记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 分页器 -->
    <el-row style="marginTop: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[6, 20, 50, 100, 500]"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑"
      :close-on-click-modal="false"
      :visible.sync="dialogModifyThemeFormVisible"
      width="600px"
      center
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        style="width: 80%"
        label-width="100px"
      >
        <el-form-item label="处置方式:" prop="handler_message">
          <el-select
            style="width: 50%"
            size="mini"
            v-model="form.handler_message"
            placeholder="待处理"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="处置详情:" prop="message_commit">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            v-model="form.message_commit"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modifyRowThemeAction('form')"
          >提交</el-button
        >
        <el-button @click="dialogModifyThemeFormVisible = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 记录弹窗 -->
    <el-dialog
      title="操作记录"
      :close-on-click-modal="false"
      :visible.sync="dialogModifyThemeFormVisible2"
      center
    >
      <el-table
        :data="tableData2"
        v-loading="loading_Record"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column
          prop="handler_time"
          label="时间"
          align="center"
          width="160"
        >
        </el-table-column>
        <el-table-column
          prop="record1"
          label="处理情况"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column prop="record2" label="处理详情" align="center">
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 轨迹详情弹窗 -->
    <el-dialog
      title="轨迹详情"
      :close-on-click-modal="false"
      :visible.sync="dialogModifyThemeFormVisible4"
      width="1200px"
      center
    >
      <el-table
        :data="tableData4"
        v-loading="loading_path"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
        style="width: 100%"
        height="480"
      >
        <el-table-column
          prop="sm_time"
          label="时间"
          align="center"
          width="200px"
        >
        </el-table-column>
        <el-table-column
          prop="sm_color"
          label="码色"
          align="center"
          width="120px"
        >
        </el-table-column>
        <el-table-column
          prop="jingwei_place"
          label="地点"
          align="center"
          width="400px"
        >
        </el-table-column>
        <el-table-column prop="jingwei" label="经纬度" align="center">
        </el-table-column>
      </el-table>
      <!-- 轨迹详情分页器 -->
      <el-pagination
        style="marginTop: 20px"
        background
        @current-change="handleCurrentChange_path"
        :current-page.sync="currentPage_path"
        :page-size="pageSize_path"
        layout="total, prev, pager, next"
        :total="total_path"
        :hide-on-single-page="true"
      >
      </el-pagination>
    </el-dialog>

    <!-- 输入密码弹窗 -->
    <el-dialog
      title="输入密码"
      :close-on-click-modal="false"
      :visible.sync="dialogModifyThemeFormVisible3"
      width="600px"
      center
    >
      <el-form
        :model="form2"
        :rules="rules2"
        ref="form2"
        style="width: 80%"
        label-width="80px"
      >
        <el-form-item label="账号:" prop="userName">
          <el-input
            placeholder="请输入账号"
            v-model="form2.userName"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码:" prop="password">
          <el-input
            placeholder="请输入密码"
            type="password"
            v-model="form2.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getSubmit('form2')">下一步</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  data() {
    return {
      currentPage: 1, // 当前页
      pageSize: 6, // 每页记录数
      total: 0, // 总条数
      keyWord: "",
      select_datetime: [], // 选择的时间范围
      startTime: "",
      endTime: "",
      tableData: [], // 列表
      tableData2: [], // 操作记录列表
      tableData4: [], // 轨迹详情列表
      options: [
        {
          value: "1",
          label: "集中隔离",
        },
        {
          value: "2",
          label: "居家隔离",
        },
        {
          value: "3",
          label: "居家监测",
        },
        {
          value: "4",
          label: "发送协查",
        },
        {
          value: "5",
          label: "正常管理",
        },
        {
          value: "6",
          label: "闭环管理",
        },
        {
          value: "7",
          label: "自我监测",
        },
        {
          value: "8",
          label: "其他情况",
        }
      ],
      people_value: [],
      people_state: 1,
      state_options: [
        {
          value: 0,
          label: "未处置",
        },
        {
          value: 1,
          label: "已处置",
        },
      ],
      color_value: "",
      handlerMsg: "",
      myArr: [],
      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]);
            },
          },
        ],
      },
      dialogModifyThemeFormVisible: false,
      dialogModifyThemeFormVisible2: false,
      dialogModifyThemeFormVisible3: false,
      dialogModifyThemeFormVisible4: false,
      form: {
        id: "",
        uuid: "",
        handler_message: "",
        sm_time: "",
        message_commit: "",
      },
      rules: {
        handler_message: [
          { required: true, message: "请选择处置方式", trigger: "change" },
        ],
        message_commit: [
          { required: true, message: "请输入处置详情", trigger: "blur" },
        ],
      },
      form2: {
        userName: "",
        password: "",
      },
      rules2: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
      },
      loading: false,
      loading_path: false,
      loading_Record: false,
      currentPage_path: 1, // 轨迹详情当前页
      pageSize_path: 8, // 轨迹详情每页记录数
      total_path: null, // 轨迹详情总条数
      uuid_Path: "",
      sm_time_Path: "",
      temObj: {
        // sm_time:"",
        // sm_color:"",
        // jingwei_place:"",
        // jingwei:"",
      },
    };
  },
  created() {
    // 初始化日期为昨天 至 今天
    this.initDate();
  },
  methods: {
    //  初始化日期时间
    initDate() {
      //当前设定的日期时间
      let d = new Date();
      var year1 = d.getFullYear(); // 获取当前年份
      var mon1 = d.getMonth() + 1; // 获取当前月份
      var day1 = d.getDate(); // 获取当前日

      //前一天设定的日期时间
      d.setTime(d.getTime() - 24 * 60 * 60 * 1000);
      var year2 = d.getFullYear(); // 获取当前年份
      var mon2 = d.getMonth() + 1; // 获取当前月份
      var day2 = d.getDate(); // 获取当前日

      this.startTime = this.getDate(year2, mon2, day2);
      this.endTime = this.getDate(year1, mon1, day1);

      this.select_datetime.push(this.startTime);
      this.select_datetime.push(this.endTime);

      this.handleCurrentChange();
    },
    // 获取指定格式 年、月、日
    getDate(y, m, d) {
      m = m > 9 ? m : "0" + m;
      d = d > 9 ? d : "0" + d;

      return y + "-" + m + "-" + d;
    },
    // 整理参数
    handleCurrentChange(val = 1) {
      this.currentPage = val;
      var params = {
        handler_state2: this.people_state,
        page: this.currentPage,
        rows: this.pageSize,
        name: !this.keyWord ? null : this.keyWord,
      };
      if ((this.startTime != "") & (typeof this.startTime != "undefined")) {
        params.startTime = this.startTime;
      }
      if ((this.endTime != "") & (typeof this.endTime != "undefined")) {
        params.endTime = this.endTime;
      }
      this.get_list(params);
    },
    // 获取列表数据
    get_list(params) {
      this.loading = true;
      this.$axios
        .get("/bigData2/userqueryCz.action", {
          params: params,
        })
        .then((res) => {
          // console.log(res);
          if (res.status === 200) {
            res.data.rows.forEach((element) => {
              element.leixing = "";
              if (element.ishot === "1") {
                element.leixing = "发热人员";
              }
              if (element.iskey === "1") {
                element.leixing += "重点区域人员";
              }
              if (element.istoken === "1") {
                if (element.leixing === "") {
                  element.leixing = "脱管人员";
                } else {
                  element.leixing += "，脱管人员";
                }
              }
              if (element.handler_unit === "县指挥部防疫组") {
                element.handler_unit =
                  element.handler_unit + "," + element.town;
              } else {
                element.handler_unit = "县指挥部防疫组," + element.town;
              }
              this.myArr.push({
                label: "",
              });
              return element;
            });
            this.tableData = res.data.rows;
            this.total = res.data.total;
          } else {
            this.$message.success("获取列表数据失败");
          }
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error("数据请求异常:没有符合条件的数据");
          this.tableData = [];
          this.loading = false;
        });
    },
    // 点击编辑按钮事件
    handleThemeModifyClick(row) {
      // console.log(row);
      this.form.uuid = row.uuid;
      this.form.id = row.id;
      this.form.sm_time = row.sm_time;
      this.form.handler_message = "";
      this.form.message_commit = "";
      this.dialogModifyThemeFormVisible = true;
      //   this.formThemeModify = JSON.parse(JSON.stringify(row));
      //   if (row.enable === "是") {
      //     this.formThemeModify.enable = "1";
      //   } else {
      //     this.formThemeModify.enable = "2";
      //   }
    },

    modifyRowThemeAction(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogModifyThemeFormVisible3 = true;
        } else {
          console.log("提交失败!!");
          return false;
        }
      });
    },

    async getSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res = await this.$axios({
            url: "/diseaseRight/adminInfo/login",
            method: "post",
            params: this.form2,
          });
          if (res.data.success) {
            let result = await this.$axios({
              url: "/bigData2/userupdateHands.action",
              method: "post",
              params: this.form,
            });
            // console.log(result);
            if (result.data.code == 200) {
              this.$message.success(result.data.msg);
            } else {
              this.$message.error(result.data.msg);
            }
            this.dialogModifyThemeFormVisible3 = false;
            this.dialogModifyThemeFormVisible = false;
            this.handleCurrentChange(1);
          } else {
            this.$message.error(res.data.message);
          }
        } else {
          console.log("提交失败!!");
          return false;
        }
      });
    },

    // 点击记录按钮事件
    async deleteTitle(row) {
      this.dialogModifyThemeFormVisible2 = true;
      this.tableData2 = [];
      this.loading_Record = true;

      let params = {
        uuid: row.uuid,
      };
      let res = await this.$axios({
        url: "/bigData2/userqueryRecordsByU.action",
        method: "post",
        params,
      });
      // console.log(res);
      if (res.data.code == 200) {
        this.tableData2 = res.data.data.reverse();
      } else {
        console.log("获取 操作记录 失败");
      }
      this.loading_Record = false;
    },

    // 点击轨迹详情按钮事件
    guiXiang(row) {
      this.temObj = { ...row };
      this.dialogModifyThemeFormVisible4 = true;
      this.uuid_Path = row.uuid;
      this.sm_time_Path = row.sm_time;
      this.currentPage_path = 1;
      this.getPathData();
    },
    // 获取轨迹详情数据
    async getPathData() {
      this.loading_path = true;
      this.tableData4 = [];
      this.total_path = null;
      let params = {
        uuid: this.uuid_Path,
        sm_time: this.sm_time_Path,
        page: this.currentPage_path,
        rows: this.pageSize_path,
      };
      let res = await this.$axios({
        url: "/bigData2/userqueryGuijiPage.action",
        method: "post",
        params,
      });
      // console.log(res);
      if (res.status == 200) {
        if (params.page == 1) {
          this.tableData4 = res.data.rows;
          if (this.tableData4) {
            this.tableData4.unshift(this.temObj);
          }else{
            this.tableData4=[]
            this.tableData4.push(this.temObj)
          }
        } else {
          this.tableData4 = res.data.rows;
        }
        this.total_path = res.data.total;
        this.currentPage_path = params.page;
      } else {
        console.log("获取 轨迹详情 失败");
      }
      this.loading_path = false;
    },
    // 服务器端导出excel
    exportServerExcel() {
      var params = {};
      if (
        (this.people_value != "") &
        (typeof this.people_value != "undefined")
      ) {
        for (var i = 0; i < this.people_value.length; i++) {
          if (this.people_value[i] === "1") {
            params.iskey = 1;
          } else if (this.people_value[i] === "2") {
            params.istoken = 1;
          } else if (this.people_value[i] === "3") {
            params.ishot = 1;
          }
        }
      }

      if (
        (this.people_state != "") &
        (typeof this.people_state != "undefined")
      ) {
        for (var i = 0; i < this.people_state.length; i++) {
          if (this.people_state[i] === "1") {
            params.handler_state2 = 0;
          } else if (this.people_state[i] === "2") {
            params.handler_state2 = 1;
          }
        }
      }

      if ((this.color_value != "") & (typeof this.color_value != "undefined")) {
        if (this.color_value === "1") {
          params.sm_color = "红码";
        } else if (this.color_value === "2") {
          params.sm_color = "黄码";
        } else if (this.color_value === "3") {
          params.sm_color = "绿码";
        }
      }

      if ((this.startTime != "") & (typeof this.startTime != "undefined")) {
        params.startTime = this.startTime;
      }

      if ((this.endTime != "") & (typeof this.endTime != "undefined")) {
        params.endTime = this.endTime;
      }

      var _this = this;
      _this.$axios
        .post("/bigData2/usertoExcel.action", {
          data: params,
        })
        .then((res) => {
          // console.log(res.data);
          if (res.data.code === 200) {
            const a = document.createElement("a");
            a.setAttribute("target", "_blank");
            a.setAttribute("href", res.data.downurl);
            a.click();
          } else {
            _this.$message.success("【导出】地址无效！");
          }
        })
        .catch((err) => {
          // console.log(err);
          _this.$message.error("【导出】异常: " + err);
        });
    },
    // 导出客户端的表格数据
    exportExcel(param) {
      /* generate workbook object from table */
      var xlsxParam = {
        raw: true,
      }; // 导出的内容只做解析，不进行格式转换
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#exportTab"),
        xlsxParam
      );

      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: "application/octet-stream",
          }),
          "重点人员_导出数据_" +
            param +
            this.startTime +
            "～" +
            this.endTime +
            ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },

    // 选择起止日期
    dateChange(val) {
      this.startTime = val[0];
      this.endTime = val[1];
      this.handleCurrentChange(1);
    },
    // 处置情况
    stateChange(val) {
      this.people_state = val;
      this.handleCurrentChange(1);
    },

    // 处理情況
    handleShowDialog(index, row) {
      var _this = this;
      _this.handlerMsg = _this.myArr[index].label;
      _this
        .$confirm("是否现在处理？", "提示", {
          confirmButtonText: "处理",
          cancelButtonText: "暂不处理",
          type: "warning",
          showInput: true,
          inputPlaceholder: "请输入处置详情",
        })
        .then((_) => {
          if (_.action == "confirm") {
            var params = {
              uuid: row.uuid,
              id: row.id,
              handler_message: _this.handlerMsg,
              sm_time: _this.tableData[index].sm_time,
              message_commit: _.value,
            };
            _this.$axios
              .get("/bigData2/userupdateHand.action", {
                params: params,
              })
              .then((res) => {
                // console.log(res.data);
                if (res.data.code === 200 && res.data.msg == "更新成功") {
                  _this.$message.success("【处理】成功！");
                  this.myArr = [];
                  _this.handleCurrentChange();
                  // 滚动到之前位置
                  setTimeout(() => {
                    _this.$refs.tableList.bodyWrapper.scrollTop =
                      (_this.$refs.tableList.bodyWrapper.scrollHeight /
                        _this.tableData.length) *
                      (index - 1);
                  }, 1000);
                } else {
                  _this.$message.error(res.data.msg);
                }
              })
              .catch((err) => {
                // console.log(err);
                _this.$message.error("【处理】请求异常: " + err);
              });
          }
        })
        .catch((_) => {
          _this.$message.warning("【处理】请求被取消！");
          this.$set(this.myArr[index], "label", "");
        });
    },

    // 改变每页条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange();
    },
    // 搜索框搜索回调
    handleSearch() {
      if (this.keyWord) {
        this.handleCurrentChange(1);
      }
    },
    // 搜索框清空回调
    handleClear() {
      this.handleCurrentChange(1);
    },
    //  轨迹详情弹窗换页逻辑
    handleCurrentChange_path(val) {
      this.currentPage_path = val;
      this.getPathData();
    },
  },
};
</script>

<style scoped>
@import url("zhongdianrenyuan.css");
</style>
