<template>
  <div class="my-agency all-select-btn" data-testid="my-agency-container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" data-testid="my-agency-search-form">
      <el-form-item label="事件名称：">
        <el-input v-model="formInline.eventName" data-testid="my-agency-event-name-input"> </el-input>
      </el-form-item>
      <el-form-item label="发生位置：">
        <el-input v-model="formInline.keyword" placeholder="请输入" data-testid="my-agency-keyword-input"></el-input>
      </el-form-item>
      <el-form-item label="所属工序：">
        <el-select
          v-model="formInline.productionLineId"
          placeholder="请选择"
          style="width: 180px"
          data-testid="my-agency-production-line-select"
        >
          <el-option
            v-for="(item, index) in basicConfiguration.productLineList"
            :key="item.productionLineId"
            :label="item.productionLineName"
            :value="item.productionLineId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型">
        <el-select
          v-model="formInline.deviceType"
          style="width: 180px"
          placeholder="请选择"
          data-testid="my-agency-device-type-select"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="(item, index) in basicConfiguration.deviceList"
            index="item.id"
            :label="item.desc"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发生时间">
        <el-date-picker
          type="datetimerange"
          v-model="formInline.createTime"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          popper-class="date-picker-popper"
          data-testid="my-agency-date-picker"
        />
      </el-form-item>
      <el-form-item>
        <el-button class="default-btn reset-btn-balck-theme" @click="onReset" data-testid="my-agency-reset-button"
          >重置</el-button
        >
        <el-button
          type="default"
          class="default-btn search-btn-balck-theme"
          @click="onSearch"
          data-testid="my-agency-search-button"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <div class="table-box" data-testid="my-agency-table-container">
      <common-table
        ref="pageRef"
        :data="tableData"
        :columns="tableColumns"
        :default-page-size="20"
        :total="total"
        @pagination-change="handlePaginationChange"
        :pagination-texts="{
          total: '共',
          sizeChange: '条/页',
          prev: '前一页',
          next: '后一页',
          jumper: '跳至',
        }"
        data-testid="my-agency-common-table"
      >
        <template #index="{ $index }">
          {{ getIndex($index) }}
        </template>
        <template #level="{ row }">
          <span class="level" :class="getColor(row.level)">
            {{ row.level }}
          </span>
        </template>
        <template #operation="{ row }">
          <span class="view-btn green-color" @click="handleDone(row)" data-testid="my-agency-process-button">
            处理
          </span>
          <span class="table-btn">|</span>
          <span class="view-btn green-color" @click="handleDispatch(row)" data-testid="my-agency-dispatch-button">
            分派
          </span>
          <span class="table-btn">|</span>
          <span class="view-btn green-color" @click="changeBag(row)" data-testid="my-agency-change-bag-button">
            更换布袋
          </span>
        </template>
      </common-table>
    </div>
    <common-dialog
      :show-dialog="doneDialog.show"
      :title="doneDialog.title"
      :width="doneDialog.width"
      :btn-group="doneDialog.btnGroup"
      @handleBtn="saveDeal"
      @close:showDialog="doneDialog.show = false"
    >
      <div class="form-box">
        <el-form ref="form" :model="formModel">
          <el-row :gutter="24">
            <el-col :span="24">
              <div class="label-title">闭环控制分派</div>
              <el-form-item label="已分派人:">
                <el-tag
                  v-for="(ele, eIndex) in personTag"
                  :key="ele.name"
                  :type="ele.type"
                >
                  {{ ele.name }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <div class="label-title">闭环控制信息</div>
              <div class="alarm-content">
                <div class="content-item">
                  <span class="name">编号:</span>
                  <span class="value">{{ workSheetDetail?.workTicketNo }}</span>
                </div>
                <div class="content-item">
                  <span class="name">创建时间:</span>
                  <span class="value">{{ workSheetDetail?.createTime }}</span>
                </div>
                <div class="content-item">
                  <span class="name">闭环控制状态:</span>
                  <span class="value work-status">{{
                    workSheetDetail?.desc
                  }}</span>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" v-if="workSheetDetail?.warnType !== 5">
            <el-col :span="24">
              <div class="label-title">告警信息</div>
              <div class="alarm-content">
                <div class="content-item">
                  <span class="name">所属工序:</span>
                  <span class="value">{{
                    workSheetDetail?.productionLine || "--"
                  }}</span>
                </div>
                <div class="content-item">
                  <span class="name">发生位置:</span>
                  <span class="value">{{ workSheetDetail?.deviceName }}</span>
                </div>
                <div
                  class="content-item"
                  v-if="
                    workSheetDetail?.warnType &&
                    workSheetDetail?.warnType != 3 &&
                    workSheetDetail?.warnType != 18 &&
                    workSheetDetail?.warnType != 9 &&
                    ((workSheetDetail?.warnType != 99 &&
                      workSheetDetail?.warnType != 4 &&
                      workSheetDetail?.warnType != 20 &&
                      workSheetDetail?.warnType != 21) ||
                      workSheetDetail?.warnType == 4)
                  "
                >
                  <span
                    class="name"
                    v-if="
                      workSheetDetail?.warnType != 99 &&
                      workSheetDetail?.warnType != 4 &&
                      workSheetDetail?.warnType != 20 &&
                      workSheetDetail?.warnType != 21
                    "
                    >告警值:</span
                  >
                  <span class="name" v-else-if="workSheetDetail?.warnType == 4"
                    >离线时长:</span
                  >
                  <span
                    class="value alarm-value"
                    v-if="
                      workSheetDetail.warnType != 99 &&
                      workSheetDetail.warnType != 4 &&
                      workSheetDetail.warnType != 18
                    "
                    >{{ workSheetDetail?.value
                    }}{{ workSheetDetail?.unit }}</span
                  >
                  <span
                    class="value alarm-value"
                    v-else-if="workSheetDetail?.warnType == 4"
                    >{{ warnValueFilter(workSheetDetail?.offlineTime) }}</span
                  >
                </div>
                <div class="content-item" v-if="workSheetDetail?.convertValue">
                  <span class="name">折算值:</span>
                  <span class="value alarm-value"
                    >{{ workSheetDetail?.convertValue
                    }}{{ workSheetDetail?.unit }}</span
                  >
                </div>
                <div class="content-item">
                  <span class="name">告警时间:</span>
                  <span class="value">{{ workSheetDetail.eventTime }}</span>
                </div>
                <div
                  class="content-item"
                  v-if="
                    workSheetDetail?.warnType &&
                    workSheetDetail?.warnType != 3 &&
                    workSheetDetail?.warnType != 9 &&
                    workSheetDetail?.warnType != 20 &&
                    workSheetDetail?.warnType != 21 &&
                    workSheetDetail?.warnType != 100 &&
                    workSheetDetail?.warnType != 150 &&
                    workSheetDetail?.warnType != 18
                  "
                >
                  <span class="name">当前监测值:</span>
                  <span class="value cur-alarm-value">
                    {{ workSheetDetail.realtimeValue || "--"
                    }}{{ workSheetDetail.unit }}
                  </span>
                </div>
                <div
                  class="content-item"
                  v-if="
                    workSheetDetail?.warnType &&
                    workSheetDetail?.warnType != 3 &&
                    workSheetDetail?.warnType != 9
                  "
                >
                  <span class="name">告警指标:</span>
                  <span class="value">{{ workSheetDetail.metric }}</span>
                </div>
                <div
                  class="content-item"
                  v-if="
                    workSheetDetail?.warnType &&
                    workSheetDetail?.warnType != 3 &&
                    workSheetDetail?.warnType != 9
                  "
                >
                  <span class="name">告警级别:</span>
                  <div
                    class="value"
                    :class="getColor(workSheetDetail.level)"
                  ></div>
                </div>
                <div
                  class="content-item new-content-item-style"
                  v-if="workSheetDetail.metric == 'TSP浓度'"
                >
                  <span class="name change-style">TSP粉尘污染溯源结果:</span>
                  <span class="value">{{
                    workSheetDetail.sourceTrace || "无"
                  }}</span>
                </div>
                <div
                  class="content-item"
                  v-if="
                    workSheetDetail?.warnType && workSheetDetail?.warnType == 18
                  "
                >
                  <span class="name">故障类型:</span>
                  <span class="value">
                    {{ viewData[workSheetDetail.cemsBreakdownTag] }}
                  </span>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" v-if="workSheetDetail?.relationAnalysis">
            <el-col :span="24">
              <div class="label-title">数据异常定位分析</div>
              <div class="alarm-content">
                <div class="content-item">
                  <span class="name">离线原因:</span>
                  <span class="value">{{
                    workSheetDetail.analysisMessage || "--"
                  }}</span>
                </div>
                <div class="content-item">
                  <el-button
                    type="primary"
                    style="margin-left: 80px"
                    class="led-btn"
                    @click="openPage(workSheetDetail)"
                    >关联台账</el-button
                  >
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24" v-if="workSheetDetail?.warnType === 5">
            <el-col :span="24">
              <div class="label-title">道路信息</div>
              <div class="alarm-content">
                <div class="content-item">
                  <span class="name">发生位置:</span>
                  <span class="value">
                    {{
                      workSheetDetail.analyzeResult &&
                      workSheetDetail.analyzeResult.roadName
                        ? workSheetDetail.analyzeResult.roadName
                        : "--"
                    }}
                  </span>
                </div>
                <div class="content-item">
                  <span class="name">全厂PM10均值:</span>
                  <span class="value">
                    {{
                      workSheetDetail.analyzeResult &&
                      workSheetDetail.analyzeResult.pm10AvgFactory
                        ? workSheetDetail.analyzeResult.pm10AvgFactory +
                          " μg/m³"
                        : "--"
                    }}
                  </span>
                </div>
                <div class="content-item">
                  <span class="name">统计时间:</span>
                  <span class="value">
                    {{
                      workSheetDetail.analyzeResult
                        ? workSheetDetail.analyzeResult.startTime +
                          "—" +
                          workSheetDetail.analyzeResult.endTime
                        : ""
                    }}
                  </span>
                </div>
                <div class="content-item">
                  <span class="name">PM10均值:</span>
                  <span class="value">
                    {{
                      workSheetDetail.analyzeResult &&
                      workSheetDetail.analyzeResult.pm10AvgRoad
                        ? workSheetDetail.analyzeResult.pm10AvgRoad + " μg/m³"
                        : "--"
                    }}
                  </span>
                </div>
                <div class="content-item">
                  <span class="name">道路清洁度指数:</span>
                  <template v-if="workSheetDetail.analyzeResult">
                    <div
                      v-for="(item, i) in Number(
                        workSheetDetail.analyzeResult.riskLevel
                      )
                        ? Number(workSheetDetail.analyzeResult.riskLevel)
                        : 0"
                      :key="i"
                    >
                      <span
                        v-if="Number(workSheetDetail.analyzeResult.riskLevel)"
                      >
                        <img src="@/assets/star.png" alt="⭐️" />
                      </span>
                    </div>
                  </template>

                  <div
                    v-if="
                      workSheetDetail.analyzeResult &&
                      workSheetDetail.analyzeResult.riskLevel == '-'
                    "
                  >
                    <span class="value">
                      {{ workSheetDetail.analyzeResult.riskLevel }}
                    </span>
                  </div>
                </div>
                <div class="content-item">
                  <span class="name">VDM均值:</span>
                  <span class="value">
                    {{
                      workSheetDetail.analyzeResult &&
                      workSheetDetail.analyzeResult.vdmAvgRoad
                        ? workSheetDetail.analyzeResult.vdmAvgRoad + " μg/m³"
                        : ""
                    }}
                  </span>
                </div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="24" v-if="workSheetDetail?.alarmImags">
            <el-col>
              <div class="label-title">告警图片</div>
              <div class="demo-image__preview">
                <div
                  class="image-preview"
                  v-for="(item, index) in alarmImg"
                  :key="index"
                >
                  <el-image
                    style="width: 100px; height: 100px"
                    :lazy="true"
                    :src="item"
                    :preview-src-list="alarmImg"
                  ></el-image>
                </div>
              </div>
            </el-col>
          </el-row>

          <el-row
            :gutter="24"
            v-if="
              workSheetDetail?.forwards &&
              workSheetDetail?.forwards[0] &&
              workSheetDetail?.triggerType === 2
            "
          >
            <el-col :span="24">
              <div class="label-title">问题描述</div>
              <div class="input-style-text">
                {{ workSheetDetail.forwards[0].forward }}
              </div>
              <div class="demo-image__preview">
                <div
                  class="image-preview"
                  v-for="(item, index) in imgUrlList"
                  :key="index"
                >
                  <el-image
                    style="width: 100px; height: 100px"
                    :lazy="true"
                    :src="item"
                    :preview-src-list="imgUrlList"
                  ></el-image>
                </div>
              </div>
              <div
                class="input-style-text"
                v-if="
                  !workSheetDetail?.forwards[0]?.forward &&
                  imgUrlList.length == 0
                "
              >
                暂无描述
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="24" v-if="srcList.length">
            <el-col :span="24">
              <div class="label-title">告警图片</div>
              <div class="demo-image__preview">
                <div
                  class="image-preview"
                  v-for="(item, index) in srcList"
                  :key="index"
                >
                  <el-image
                    style="width: 100px; height: 100px"
                    :lazy="true"
                    :src="item"
                    :preview-src-list="srcList"
                  ></el-image>
                </div>
              </div>
            </el-col>
          </el-row>

          <el-row
            :gutter="24"
            v-if="workSheetDetail?.warnType && workSheetDetail?.warnType == 444"
          >
            <el-col :span="24" class="deal-line-wrap">
              <div class="label-title">问题描述</div>
              <div
                class="qusetion-records"
                v-if="
                  workSheetDetail?.questionDescList &&
                  workSheetDetail?.questionDescList.length > 0
                "
              >
                <div
                  class="qusetion-records-item"
                  v-for="(item, index) in workSheetDetail?.questionDescList"
                  :key="index"
                >
                  {{ item }}
                </div>
              </div>
              <div v-else class="input-style-text">暂无数据</div>
            </el-col>
          </el-row>
          <el-row
            :gutter="24"
            v-if="functionAuthority && functionAuthority?.close_loop_upgrade"
          >
            <el-col :span="24" class="deal-line-wrap">
              <div class="label-title">落实管理制度</div>
              <div
                class="processing-records"
                :class="[
                  workSheetDetail?.levelManageList.length == 1
                    ? 'one-record'
                    : '',
                ]"
                v-if="
                  workSheetDetail?.levelManageList &&
                  workSheetDetail?.levelManageList.length > 0
                "
              >
                <div
                  class="processing-records-item"
                  v-for="(item, index) in workSheetDetail?.levelManageList"
                  :key="index"
                >
                  <div class="steps-line">
                    <div class="header" v-show="index !== 0"></div>
                    <div
                      class="footer"
                      v-show="
                        index !== workSheetDetail?.levelManageList.length - 1
                      "
                    ></div>
                  </div>
                  <span class="handler">{{ item.userName }}</span>
                  <span class="circle"></span>
                  <span class="step-name">
                    {{
                      item.state == 0
                        ? "处理中"
                        : item.state == 1
                        ? "已处理"
                        : ""
                    }}
                  </span>
                  <span class="partment">{{ item.officeName || "无" }}</span>
                  <span class="handler-time">{{ item.date }}</span>
                </div>
              </div>
              <div v-else class="input-style-text">暂无数据</div>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <div class="label-title">原因分析</div>
              <el-input
                class="input-style"
                v-model="dialogReason"
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
              />
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <div class="label-title">处理措施</div>
              <div>
                <el-input
                  class="input-style"
                  v-model="dialogMeasure"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入内容"
                />
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </common-dialog>
    <common-dialog
      :showDialog="assignDialog.show"
      :title="assignDialog.title"
      :btn-group="assignDialog.btnGroup"
      :width="assignDialog.width"
      @handleBtn="saveAssign"
      @close:showDialog="assignDialog.show = false"
    >
      <el-form>
        <el-form-item label="分派人:">
          <div class="inline-box">
            <el-select
              v-model="handlerPeopleId"
              filterable
              placeholder="请选择分派人"
            >
              <el-option
                v-for="(item, i) in handlerPeople"
                :key="i"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-button
              type="default"
              class="addBtn search-btn-balck-theme"
              @click="addPerson"
              >新增</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="已分派人:">
          <el-tag
            v-for="(ele, eIndex) in personTag"
            :key="ele.name"
            closable
            @close="delPerson(eIndex)"
            :type="ele.type"
          >
            {{ ele.name }}
          </el-tag>
        </el-form-item>
      </el-form>
    </common-dialog>
    <common-dialog
      :show-dialog="bagDialog.show"
      :title="bagDialog.title"
      :btn-group="bagDialog.btnGroup"
      :width="bagDialog.width"
      @handleBtn="saveBag"
      @close:showDialog="bagDialog.show = false"
    >
      <el-form>
        <el-form-item label="第几行：">
          <el-select
            v-model="bagRow"
            placeholder="请选择第几行"
            @change="getCol"
          >
            <el-option
              v-for="item in rowList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="第几列：">
          <el-select v-model="bagCol" placeholder="请选择第几列">
            <el-option
              v-for="item in colList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from "vue";
import CommonTable from "@/components/commonTable/index.vue";
import commonDialog from "./components/dialog.vue";
import {
  getData,
  getDataFun,
  postData,
  postDataJson,
  postDataJSON,
} from "@/request/method.js";
import moment from "moment";
import { getToken } from "@/utils/auth.js";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { useUsersStore } from "@/pinia/user.js";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();

const { functionAuthority } = storeToRefs(useUsersStore());
const total = ref(0);
const formInline = ref({
  eventName: "",
  keyword: "",
  warnType: "",
  productionLineId: "",
  deviceType: "",
  createTime: route.query.startTime
    ? [
        moment(new Date(route.query.startTime).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        moment(new Date(route.query.endTime).getTime()).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
      ]
    : ["", ""],
});

const workTicketNo = ref("");

const handlerPeopleId = ref("");
const handlerPeople = ref([]);

const getHandlerPeople = async () => {
  const url = "/transfer-work-ticket-pc/getTicketHandler?pageSize=999&pageNo=1";
  try {
    let result = await getData(url);
    if (result && result.code === 1) {
      const { records } = result.data;
      handlerPeople.value = records;
    }
  } catch (e) {
    ElMessage({
      message: "接口报错",
      type: "error",
    });
  }
};

const assignDialog = ref({
  title: "闭环控制分派",
  show: false,
  width: "30%",
  btnGroup: [
    {
      attrKey: "save",
      label: "保存",
    },
  ],
});

const bagDialog = ref({
  title: "更换布袋",
  show: false,
  width: "30%",
  btnGroup: [
    {
      attrKey: "save",
      label: "保存",
    },
  ],
});

const bagRow = ref("");
const bagCol = ref("");
const rowList = ref([]);
const colList = ref([]);

const saveBag = () => {
  if (bagRow.value === "") {
    ElMessage({
      type: "warning",
      message: "请选择第几行",
    });
    return;
  }
  if (bagCol.value === "") {
    ElMessage({
      type: "warning",
      message: "请选择第几列",
    });
    return;
  }
  const params = {
    workTicketNo: workTicketNo.value,
    row: bagRow.value,
    column: bagCol.value,
  };
  postDataJSON("/transaction/doc/changeBag", params).then((res) => {
    if (res.code === 1) {
      ElMessage({
        type: "success",
        message: "更换布袋成功",
      });
      bagDialog.value.show = false;
      searchData();
    }
  });
};
const rowLineMap = ref(null);
const getBagRowLine = (no) => {
  const url = "/bag/cycle/getCompartEnumList";
  const params = {
    deviceNo: no,
  };
  getDataFun(url, params).then((res) => {
    if (res.code === 1) {
      rowLineMap.value = res.data;
      res.data.forEach((item) => {
        rowList.value.push(item.row);
      });
    }
  });
};

const getCol = () => {
  rowLineMap.value.forEach((item) => {
    if (item.row === bagRow.value) {
      colList.value = item.columns;
    }
  });
};

const personTag = ref([]);

const addPerson = () => {
  const target = handlerPeople.value.find(
    (item) => item.id === handlerPeopleId.value
  );
  personTag.value.push({
    userId: target.id,
    userName: target.name,
    name: target.name,
    type: "info",
  });
};

const delPerson = (index) => {
  personTag.value.splice(index, 1);
};

const getIndex = (index) => {
  return (currentPage.value - 1) * pageSize.value + index + 1;
};

const saveAssign = () => {
  if (personTag.value.length === 0) {
    ElMessage({
      showClose: true,
      type: "warning",
      message: "请选择分派人",
    });
  }
  const tempArr = [];
  personTag.value.forEach((item) => {
    tempArr.push({
      userId: item.userId,
      userName: item.userName,
    });
  });
  const params = {
    workTicketNo: workTicketNo.value,
    receiveUser: "",
    receiveUserName: "",
    handleUsers: tempArr,
  };
  const url = "/transaction/doc/transferTransaction";
  dispatchHandle(url, params);
};

const dispatchHandle = async (url, param) => {
  try {
    let result = await postDataJSON(url, param);
    if (result && result.code === 1) {
      assignDialog.value.show = false;
      ElMessage({
        message: "处理成功",
        type: "success",
      });
      searchData();
    }
  } catch (e) {}
};

const basicConfiguration = reactive({
  ticketEventName: [{ name: "全部", id: "" }],
  eventTypeList: [],
  productLineList: [{ productionLineName: "全部", productionLineId: "" }],
  deviceList: [],
});

const workSheetDetail = ref(null);

const getColor = computed(() => {
  return (level) => {
    if (level == 2) {
      return "red";
    } else if (level == 1) {
      return "yellow";
    } else {
      return "purple";
    }
  };
});

const warnValueFilter = computed(() => {
  return (offlineTime) => {
    if (offlineTime == null || offlineTime <= 0) {
      return "--";
    }
    if (offlineTime < 60) {
      return offlineTime + "分钟";
    }
    if (offlineTime < 1440) {
      if (offlineTime % 60 == 0) {
        return offlineTime / 60 + "小时";
      } else {
        return (
          parseInt(offlineTime / 60) + "小时" + (offlineTime % 60) + "分钟"
        );
      }
    } else {
      let s;
      let d = parseInt(offlineTime / 60 / 24);
      let h = parseInt((offlineTime / 60) % 24);
      let m = offlineTime % 60;
      s = d + "天";
      if (h >= 1) {
        s += h + "小时";
      }
      if (m > 0) {
        s += m + "分钟";
      }
      return s;
    }
  };
});
const pageRef = ref(null);
const onSearch = () => {
  currentPage.value = 1;
  pageRef.value.setCurrentPage(currentPage.value);
  searchData();
};
const onReset = () => {
  currentPage.value = 1;
  pageSize.value = 20;
  formInline.value.eventName = "";
  formInline.value.keyword = "";
  formInline.value.productionLineId = "";
  formInline.value.deviceType = "";
  formInline.value.createTime = ["", ""];
  pageRef.value.setCurrentPage(currentPage.value);
  searchData();
};

const doneDialog = ref({
  title: "闭环控制分派",
  show: false,
  width: "45%",
  btnGroup: [
    {
      attrKey: "save",
      label: "处理",
    },
  ],
});

const viewData = {
  D: "在线监控(监测)仪器仪表故障",
  B: "在线监控(监测)仪器仪表与数采通讯异常",
  VGD: "在线监控(监测)仪器仪表与数采通讯异常",
};

const handleDone = async (data) => {
  doneDialog.value.title = data.eventName;
  workTicketNo.value = data.workTicketNo;
  let res = await getDetail(data.workTicketNo);
  doneDialog.value.show = true;
  personTag.value = [];
  if (res.handleUsers && res.handleUsers.length > 0) {
    res.handleUsers.forEach((item) => {
      personTag.value.push({
        type: "info",
        name: item.userName,
        userId: item.userId,
        userName: item.userName,
      });
    });
  }
  disposeWorkSheetDetail(res);
};

const saveDeal = () => {
  const { workTicketNo, handleValue, imgUrl } = workSheetDetail.value;
  const reason = dialogReason.value;
  const measure = dialogMeasure.value;
  const param = { workTicketNo, handleValue, reason, measure, imgUrl };
  const url = "/transaction/doc/finishTransaction";
  disposeHandle(url, param);
};

const disposeHandle = async (url, param) => {
  try {
    let result = await postDataJson(url, param);
    if (result && result.code === 1) {
      doneDialog.value.show = false;
      searchData();
      ElMessage({
        message: "处理成功",
        type: "success",
      });
    }
  } catch (e) {
    ElMessage({
      message: "处理失败",
      type: "error",
    });
  }
};

// 分派
const handleDispatch = async (data) => {
  getHandlerPeople();
  workTicketNo.value = data.workTicketNo;
  let res = await getDetail(data.workTicketNo);
  assignDialog.value.show = true;
  personTag.value = [];
  if (res.handleUsers && res.handleUsers.length > 0) {
    res.handleUsers.forEach((item) => {
      personTag.value.push({
        type: "info",
        name: item.userName,
        userId: item.userId,
        userName: item.userName,
      });
    });
  }
};

const getDetail = (workTicketNo) => {
  return new Promise((resolve, reject) => {
    const url = "/transaction/doc/detail";
    const params = {
      workTicketNo,
    };
    getDataFun(url, params)
      .then((res) => {
        workSheetDetail.value = res.data;
        resolve(res.data);
      })
      .catch((err) => {
        reject();
      });
  });
};

const changeBag = (data) => {
  workTicketNo.value = data.workTicketNo;
  getBagRowLine(data.deviceNo);
  bagDialog.value.show = true;
};

const tableData = ref([]);

const tableColumns = ref([
  {
    prop: "index",
    label: "序号",
    width: "6%",
  },
  {
    prop: "workTicketNo",
    label: "编号",
    width: "10%",
  },
  {
    prop: "eventName",
    label: "事件名称",
    width: "10%",
  },
  {
    prop: "deviceName",
    label: "发生位置",
    width: "10%",
  },
  {
    prop: "deviceNo",
    label: "设备编码",
    width: "10%",
  },
  {
    prop: "typeName",
    label: "设备类型",
    width: "10%",
  },
  {
    prop: "signalName",
    label: "信号名称",
    width: "10%",
  },
  {
    prop: "productionLine",
    label: "所属工序",
    width: "10%",
  },
  { prop: "warnTypeName", label: "类型", width: "10%" },
  { prop: "createTime", label: "发生时间", width: "10%" },
  { prop: "desc", label: "闭环状态", width: "10%" },
  { prop: "handleUser", label: "处理人", width: "10%" },
  { prop: "level", label: "级别", width: "5%" },
  {
    prop: "operation",
    label: "操作",
    width: "15%",
  },
]);

const customerId = getToken("customerId");

const getWarnAndTicketConfigMap = () => {
  const url = "/system/getWarnAndTicketConfigMap";
  const params = {
    customerId,
  };
  getDataFun(url, params).then((res) => {
    if (res && res.code === 1) {
      const { ticketEventName } = res.data;
      basicConfiguration.ticketEventName =
        basicConfiguration.ticketEventName.concat(ticketEventName);
    }
  });
};

const getDeviceType = () => {
  const url = "/alarm/getDeviceType";
  getData(url).then((res) => {
    basicConfiguration.deviceList = res.data;
  });
};

let realBtn = "";

const searchData = () => {
  currentPage.value = 1;
  pageSize.value = 20;
  getTableData();
};

const getTableData = () => {
  let keyWord = formInline.value.keyword;
  const params = {
    eventName: formInline.value.eventName,
    warnType: formInline.value.warnType,
    createStartTime: formInline.value.createTime[0],
    createEndTime: formInline.value.createTime[1],
    productionLineId: formInline.value.productionLineId,
    keyword: keyWord,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    handleState: 1,
    belongTo: 1,
    isDcTom: 1,
    deviceType: formInline.value.deviceType,
  };
  tableData.value = [];
  const url = "/transaction/doc/getListParamPage";
  getDataFun(url, params).then((res) => {
    if (res && res.code === 1) {
      const { list } = res.data;
      total.value = res.data.total;
      disposeType(list);
      tableData.value = list;
      tableData.value.forEach((item) => {
        item.handleUser = "";
        item.handleUsers.forEach((ele, eIndex) => {
          if (eIndex > 0) {
            item.handleUser += "," + ele.userName;
          } else {
            item.handleUser += ele.userName;
          }
        });
      });
    }
  });
};

const disposeType = (list) => {
  if (list.length) {
    list.forEach((l) => {
      if (!l.deviceNo) {
        l.deviceNo = "--";
      }
      switch (l.warnType) {
        case 0:
          l.warnType = "人工提交";
          break;
        case 1:
          l.warnType = "超标";
          break;
        case 2:
          l.warnType = "超低";
          break;
        case 3:
          l.warnType = "生产治理同步率";
          break;
        case 4:
          l.warnType = "离线";
          break;
        case 5:
          l.warnType = "其他";
          break;
        case 10:
          l.warnType = "持续超标";
          break;
        case 11:
          l.warnType = "三倍超标";
          break;
        case 99:
          l.warnType = "恒值";
          break;
      }
    });
  }
};

const srcList = ref([]);

const dialogReason = ref("");
const dialogMeasure = ref("");
const imgUrlList = ref([]);
const alarmImg = ref([]);
const disposeWorkSheetDetail = (obj) => {
  const {
    reason,
    measure,
    imagParams,
    imgUrl,
    alarmImags,
    forwards,
    createId,
  } = obj;
  if (forwards.length > 0) {
    let receiveUserItem = forwards.slice(-1)[0];
  }
  dialogMeasure.value = "";
  dialogMeasure.value = "";
  srcList.value = [];
  imgUrlList.value = [];

  if (imagParams) {
    let arr = [];
    for (let item of imagParams) {
      srcList.value = arr.concat(item.url.split(";"));
    }
  }
  if (alarmImags && alarmImags.length) {
    for (let item of alarmImags) {
      alarmImg.value.push(item.imageUrl);
    }
  }
  if (imgUrl) {
    imgUrlList.value = imgUrl.split(";");
  }
};
// 其他页面跳转当前页面，携带参数初始化
const getInitParams = () => {
  if (route.query) {
    const { deviceName, suspendStartTime, suspendEndTime } = route.query;
    if (deviceName) {
      formInline.value.keyword = deviceName;
    }
    if (suspendStartTime) {
      formInline.value.createTime[0] = suspendStartTime;
    }
    if (suspendEndTime) {
      formInline.value.createTime[1] = suspendEndTime;
    }
  }
};
onMounted(() => {
  getInitParams();
  getProDuctLine();
  getWarnAndTicketConfigMap();
  getDeviceType();
  searchData();
});

const formModel = ref({
  selectReason: [],
});
const getProDuctLine = () => {
  const url = "/transaction/getProductionLine";
  getData(url).then((res) => {
    basicConfiguration.productLineList.push(...res.data);
  });
};

const currentPage = ref(1);
const pageSize = ref(20);

const handlePaginationChange = (pagination) => {
  currentPage.value = pagination.currentPage;
  pageSize.value = pagination.pageSize;
  getTableData()
};
</script>

<style scoped lang="scss">
.my-agency {
  width: 100%;
  height: calc(100% - 14px);
  box-sizing: border-box;
  background: #181d21;
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  &-bottom {
    flex: 1;
  }
  .level {
    width: 100%;
    color: #fff;
    text-align: center;
  }
  .table-box {
    height: calc(100vh - 600px);
    flex: 1;
  }
  .yellow {
    // color: #faa508;
    position: relative;
    &::before {
      content: " ";
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #ffb224;
      position: absolute;
      left: 0;
      top: 6px;
    }
  }
  .red {
    position: relative;
    &::before {
      content: " ";
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #db001d;
      position: absolute;
      left: 0;
      top: 6px;
    }
  }

  .purple {
    position: relative;
    &::before {
      content: " ";
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #aa05fa;
      position: absolute;
      left: 0;
      top: 6px;
    }
  }
  .view-btn {
    margin-right: 8px;
    cursor: pointer;
  }
  .form-box {
    height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    .label-title {
      position: relative;
      padding-left: 14px;
      margin-bottom: 20px;
      font-weight: 700;
      font-size: 19px;
      overflow: hidden;
      color: #dce0e4;
      &::before {
        content: "";
        width: 4px;
        height: 4px;
        border-radius: 50%;
        background: #36f1cd;
        position: absolute;
        left: 0px;
        top: 50%;
        transform: translateY(-50%);
      }
      &::after {
        content: "";
        width: 100%;
        height: 0px;
        position: absolute;
        border-bottom: dashed 1px #8a9199;
        left: 130px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .alarm-content {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      padding: 0px 35px;
      .content-item {
        width: 50%;
        font-size: 14px;
        font-weight: 500;
        color: #3b3b3b;
        line-height: 19px;
        min-height: 34px;
        display: flex;
        .name {
          text-align: right;
          width: 140px;
          margin-right: 10px;
          color: #8a9199;
        }
        .change-style {
          width: auto;
        }
        .value {
          color: #fff;
          flex: 1;
        }
        .alarm-value {
          color: #ff7373;
        }
        .cur-alarm-value {
          color: #086635;
        }
        .work-status {
          color: #e1971d;
        }
      }
      .new-content-item-style {
        width: 100%;
        height: auto;
      }
    }
    .improve-situation {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 50px;
      .improve-situation-item {
        width: 310px;
        height: 71px;
        border-radius: 2px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 28px;
        font-size: 24px;
        font-weight: 500;
        color: #ffffff;
        line-height: 33px;
        &:first-child {
          background: linear-gradient(
            225deg,
            rgba(255, 133, 128, 0.65) 0%,
            rgba(255, 58, 71, 0.61) 100%,
            #0049fa 100%
          );
        }
        &:last-child {
          background: linear-gradient(
            225deg,
            rgba(128, 255, 178, 0.65) 0%,
            rgba(58, 120, 255, 0.61) 100%,
            #0049fa 100%
          );
        }
        .road-cleanliness-index {
          display: flex;
          flex-direction: column;
          align-content: center;
          justify-content: center;
          .name {
            font-size: 14px;
          }
        }
        .star {
          display: flex;
          align-items: center;
          justify-content: center;
          span {
            margin-right: 5px;
          }
        }
        .value {
          padding-right: 30px;
          span {
            font-size: 14px;
            font-weight: 400;
          }
        }
      }
    }
    .tips-content {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      padding: 0px 50px;
      .content-item {
        width: 50%;
        font-size: 14px;
        font-weight: 400;
        color: #3b3b3b;
        line-height: 19px;
        min-height: 34px;
        display: flex;
        .value {
          color: #ff7373;
          font-size: 15px;
        }
      }
    }
    .leged-bg {
      position: fixed;
      left: 0;
      right: 0;
      width: 100%;
      height: 600px;
      background-color: rgba(0, 0, 0, 0.3);
      .leged-wrap {
        width: 300px;
        height: 300px;
        background-color: #fff;
      }
    }
    .processing-records {
      display: flex;
      align-items: center;
      // justify-content: space-between;
      padding: 0 40px;
      position: relative;
      &::before {
        content: "";
        // width: calc(100% - 220px);
        height: 6px;
        background: #076d4e;
        position: absolute;
        left: 50%;
        top: 48px;
        transform: translate(-50%, -50%);
        box-sizing: border-box;
      }
      .processing-records-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .handler {
          min-width: 80px;
          // max-width: 110px;
          padding: 0 5px;
          height: 26px;
          text-align: center;
          background: #bbeedf;
          box-shadow: 0px 10px 5px -7px rgba(33, 179, 134, 0.5);
          border: 1px solid #0b5a68;
          border-radius: 2px;
          line-height: 25px;
          font-size: 14px;
          font-weight: 400;
          color: #0b5a68;
          position: relative;
          margin-bottom: 10px;
          text-overflow: ellipsis;
          // overflow: hidden;
          white-space: nowrap;
          &::before {
            content: "";
            width: 8px;
            height: 8px;
            background: #bbeedf;
            border-left: 1px solid #0b5a68;
            border-bottom: 1px solid #0b5a68;
            // transform: rotate3d(90deg);
            position: absolute;
            left: 50%;
            transform: rotate(-45deg) translateX(-50%);
            bottom: -2px;
          }
        }
        .circle {
          width: 22px;
          height: 22px;
          background: #ffffff;
          box-shadow: 0px 2px 4px 0px rgba(33, 176, 179, 0.43);
          border: 1px solid #076d4e;
          position: relative;
          border-radius: 50%;
          &::before {
            content: "";
            width: 8px;
            height: 8px;
            background: #0b5a68;
            border-radius: 4px;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
          }
        }
        .header {
          width: 50%;
          height: 6px;
          background: #076d4e;
          position: absolute;
          box-sizing: border-box;
        }
        .footer {
          width: 50%;
          height: 6px;
          left: 50%;
          background: #076d4e;
          position: absolute;
          box-sizing: border-box;
        }
        .steps-line {
          top: 45px;
          width: 100%;
          position: relative;
        }
        .step-name {
          font-size: 12px;
          font-weight: 400;
          color: #0b5a68;
          line-height: 12px;
          margin-top: 8px;
          font-weight: 500;
        }
        .partment {
          font-size: 14px;
          font-weight: 400;
          line-height: 12px;
          margin-top: 8px;
        }
        .handler-time {
          text-align: center;
          font-size: 12px;
          font-weight: 400;
          color: #606060;
          line-height: 14px;
          margin-top: 5px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          padding-left: 10px;
          padding-right: 10px;
          width: 180px;
        }
        .led-btn {
          color: #fff;
        }
      }
      .mb-20 {
        margin-bottom: 20px;
      }
    }
    .label-title-content {
      width: 90%;
      padding-left: 30px;
      margin-bottom: 10px;
    }
    .deal-line-wrap {
      overflow: auto;
      width: 100%;
    }
    .qusetion-records {
      padding: 5px 20px;
      .qusetion-records-item {
        text-indent: 10px;
      }
    }
    .demo-image__preview {
      margin: 0 50px;
      display: flex;
      flex-wrap: wrap;

      .image-preview {
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }
    :deep(.el-row) {
      margin-bottom: 28px;
    }
  }
  .form-box::-webkit-scrollbar {
    width: 0px;
    height: 8px;
    background-color: #434343; /* or add it to the track */
  }

  .input-style {
    padding-left: 50px;
  }
  .input-style-text {
    padding: 0 50px;
    font-size: 14px;
    font-weight: 400;
    color: #3b3b3b;
    line-height: 24px;
  }

  .default-btn {
    width: 85px;
  }
  .search-btn {
    width: 85px;
    background-color: var(--bg-primary);
    border: 1px solid var(--success);
  }
  :deep(.el-tag) {
    margin-right: 10px;
  }
  .inline-box {
    display: flex;
    .addBtn {
      margin-left: 10px;
    }
  }
}
</style>