<template>
  <!-- 水质报警 -->
  <div class="page-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
      class="search-form_container">
      <!-- <el-form-item label="报警内容" prop="unknown">
        <el-input v-model="queryParams.question" placeholder="请输入问题内容" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="报警类型" prop="category">
        <el-select v-model="queryParams.category">
          <el-option value="" label="全部"></el-option>
          <el-option key="出水COD" value="出水COD" label="出水COD"></el-option>
          <el-option key="出水SS" value="出水SS" label="出水SS"></el-option>
          <el-option key="出水总氮" value="出水总氮" label="出水总氮"></el-option>
          <el-option key="出水总磷" value="出水总磷" label="出水总磷"></el-option>
          <el-option key="出水氨氮" value="出水氨氮" label="出水氨氮"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="报警原因" prop="reason">
        <el-select v-model="queryParams.reason">
          <el-option value="" label="全部"></el-option>
          <el-option key="出水总磷" value="出水总磷" label="出水总磷"></el-option>
          <el-option key="出水总磷" value="出水总磷" label="出水总磷"></el-option>
          <el-option key="出水总磷" value="出水总磷" label="出水总磷"></el-option>
          <el-option key="出水总磷" value="出水总磷" label="出水总磷"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="报警状态" prop="warningStatus">
        <el-select v-model="queryParams.warningStatus">
          <el-option value="" label="全部"></el-option>
          <el-option :key="item.label" :value="item.val" :label="item.label" v-for="item in warningStatus"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-card shadow="never" body-class="card-table_container">
      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
          <el-button type="primary" plain icon="plus" size="small" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="edit" size="small" :disabled="single"
            @click="handleUpdate">修改</el-button>
        </el-col> -->
        <el-col :span="1.5">
          <el-button type="danger" plain icon="delete" size="small" :disabled="multiple"
            @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="download" size="small" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="类型" align="center" prop="category" />
        <el-table-column label="报警原因" align="center" prop="reason" />
        <el-table-column label="报警值" align="center" prop="warningVal">
          <template #default="scope">
            <span style="color: red;">{{ Number(scope.row.warningVal.toFixed(2)) }} mg/L</span>
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="designVal">
          <template #default="scope">
            <span>{{ scope.row.designVal }} mg/L</span>
          </template>
        </el-table-column>
        <el-table-column label="报警级别" align="center" prop="level" />
        <el-table-column label="报警次数" align="center" prop="counts" />
        <el-table-column label="报警发起时间" align="center" prop="createTime" />
        <el-table-column label="报警关闭时间" align="center" prop="offTime" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template #default="scope">
            <el-button type="primary" text size="small" icon="view" @click="handleRecordDetails(scope)">查看记录</el-button>
            <!-- <el-button size="small" type="text" icon="edit" @click="handleUpdate(scope.row)">修改</el-button> -->
            <!-- <el-button size="small" type="primary" text icon="delete" @click="handleDelete(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog title="水质报警记录" v-model="recordVisible" width="880px" append-to-body class="chat-dialog_container">
      <el-scrollbar height="600px">
        <ChatBaseCard>
          <div class="waring-answer-wrapper">
            <dl class="message-inner warning-info_medium flex flex-col justify-between">
              <dt class="mb-[2px] font-bold text-[#1A2029]">{{ textDataSources?.title }}</dt>
              <dd v-for="item, index in textDataSources?.list" :key="index"><span
                  :class="{ 'text-[#F44C49]': item.isWarning }">{{ item.label }}： {{ item.value }}</span></dd>
            </dl>
            <div class="table-inner">
              <div class="warning-table">
                <div class="title">
                  <span>当前进水数据：</span>
                </div>
                <div class="main">
                  <el-table :data="jsTableData" style="width: 100%" size="small">
                    <el-table-column prop="流量" label="流量(m³/h)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['流量'].exceed ? 'red' : '' }">{{
      Number(scope.row['流量'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="COD(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['COD'].exceed ? 'red' : '' }">{{
      Number(scope.row['COD'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="TN(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['TN'].exceed ? 'red' : '' }">{{
      Number(scope.row['TN'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="NH3-N(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['NH3-N'].exceed ? 'red' : '' }">{{
      Number(scope.row['NH3-N'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="TP(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['TP'].exceed ? 'red' : '' }">{{
      Number(scope.row['TP'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="SS(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['SS'].exceed ? 'red' : '' }">{{
      Number(scope.row['SS'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <div class="warning-table">
                <div class="title">
                  <span>当前出水数据：</span>
                </div>
                <div class="main">
                  <el-table :data="csTableData" style="width: 100%" size="small">
                    <el-table-column prop="流量" label="流量(m³/h)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['流量'].exceed ? 'red' : '' }">{{
      Number(scope.row['流量'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="COD(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['COD'].exceed ? 'red' : '' }">{{
      Number(scope.row['COD'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="TN(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['TN'].exceed ? 'red' : '' }">{{
      Number(scope.row['TN'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="NH3-N(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['NH3-N'].exceed ? 'red' : '' }">{{
      Number(scope.row['NH3-N'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="TP(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['TP'].exceed ? 'red' : '' }">{{
      Number(scope.row['TP'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="SS(mg/L)">
                      <template #default="scope">
                        <span :style="{ color: scope.row['SS'].exceed ? 'red' : '' }">{{
      Number(scope.row['SS'].value.toFixed(2)) }}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </div>
        </ChatBaseCard>

        <section v-for="item, index in answerResult" :key="index">
          <template v-if="item.biz === 'DECISION_REPORT'">
            <ChatAnswer :loading="item.loading" :delay-loading="item.delayLoading" :toggleVisibleIcons="false" :content="item.answer"></ChatAnswer>
          </template>

          <template v-if="item.biz === 'DECISION_ALERT'">
            <ChatBaseCard :loading="item.loading" :delay-loading="item.delayLoading" :toggleVisibleIcons="false">
              <p class="mb-[15px] font-bold text-[#1A2029]">需要确定以下问题，完成决策方案：</p>
              <ul class="radio-wrapper space-y-[14px]">
                <li class="flex items-center" v-for="val, i in item.list" :key="i">
                  <p class="mr-[14px]">{{ val.mainContent }}</p>
                  <p class="radio-btn-group space-x-[14px]">
                    <span v-for="option, index in val.options"
                      :class="['radio-btn', { active: val.isActive === index }]"
                    >{{ option }}</span>
                    <!-- @click="358(item, val, index)" -->
                  </p>
                </li>
              </ul>
            </ChatBaseCard>
          </template>

          <template v-if="item.biz === 'DECISION_SIMULATE'">
            <button class="
            px-[30px] py-[10px] mb-[20px]
            rounded-[8px] 
            bg-white text-[13px] 
            text-[#5E5E5E] hover:text-[#2454FF]" :disabled="item.isDisable" @click="handleModelVisible">
              水质预测推演
            </button>
          </template>

          <template v-if="item.biz === 'DECISION_TABLE'">
            <ChatAnswer :loading="item.loading" :delay-loading="item.delayLoading" :toggleVisibleIcons="false">
              <div class="markdown-body text-[15px] break-all">
                <strong class="block mb-[16px]">推荐指标调整：</strong>
                <div class="custom-table-wrapper">
                  <table>
                    <thead>
                      <tr>
                        <th v-for="text in item.table.header" :key="text">{{ text }}</th>
                      </tr>
                    </thead>
                    <tbody class="text-center">
                      <tr>
                        <td v-for="text in item.table.body" :key="text">{{ text }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <strong class="block mb-[16px]">预测推演结果：</strong>
                <span>以上指标达成后，预计三小时内{{ flowParams.category }}可以达到：{{ item.content }}</span>
              </div>
            </ChatAnswer>
            <button class="
            px-[30px] py-[10px] mb-[20px]
            rounded-[8px] 
            bg-white text-[13px] 
            text-[#5E5E5E] hover:text-[#2454FF]" :disabled="item.isDisable" @click="handleModelVisible">
              水质预测推演
            </button>
          </template>
        </section>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import { listWarn, getWarn, delRecord } from "@/api/business/water";
import { formatToData } from "@/utils/format";
import { getRecord, addRecord, updateRecord } from "@/api/business/record";
import { ChatAsk, ChatAnswer, ChatBaseCard } from "@/components/chat"
export default {
  name: "Record",
  components: { ChatAsk, ChatAnswer, ChatBaseCard },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 信义大模型问答记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sessionId: null,
        type: null,
        module: null,
        userId: null,
        showVal: null,
        question: null,
        answer: null,
        warningId: null,
        counts: null,
        isStrong: null,
        isSatisfied: null,
        isShutdown: null,
        revision: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      warningStatus: [
        {
          val: 0,
          label: '报警中'
        },
        {
          val: 1,
          label: '历史报警'
        },
      ],
      recordVisible: false,
      textDataSources: [],
      jsTableData: [],
      csTableData: [],
      answerResult: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 查看详情
    handleRecordDetails({ row }) {
      getWarn(row.id).then(({ data }) => {
        const showVal = JSON.parse(data.showVal);
        const { basic, jsData, csData } = showVal;
        this.answerResult = [];
        try {
          const answer = JSON.parse(data.answer);
          const reportList = [];
          const alertList = [];
          let simulateObj = null;

          answer.map(item => {
            const answerObjItem = JSON.parse(item);
            switch (answerObjItem.biz) {
              case "DECISION_REPORT":
                reportList.push(answerObjItem.message);
                break
              case "DECISION_ALERT":
                alertList.push(answerObjItem);
                break
              case "DECISION_SIMULATE":
                if (row.status !== 0) return;
                const { off, on, pred } = JSON.parse(answerObjItem.message);
                simulateObj = {
                  biz: 'DECISION_SIMULATE',
                  off,
                  on,
                  pred,
                  isDisable: false
                }
                modalData.value = simulateObj;
            }
          })

          if (reportList.length) {
            this.answerResult.push({
              biz: 'DECISION_REPORT',
              answer: reportList.join(""),
              loading: false,
              delayLoading: false
            })
          }

          if (alertList.length) {
            const [parseAnswer] = alertList.map(item => {
              item.message = Object.keys(item.message).map(key => ({ ...item.message[key], isActive: null }));
              return item;
            })
            this.answerResult.push({
              biz: 'DECISION_ALERT',
              loading: false,
              delayLoading: false,
              isAllSelect: false,
              list: parseAnswer?.message
            })
          }

          if (simulateObj) {
            this.answerResult.push(simulateObj);
          }

        } catch (error) {
          this.answerResult.push({
            biz: 'DECISION_REPORT',
            answer: data.answer,
            loading: false,
            delayLoading: false
          })
          console.log("error", error);
        }

        basic.title = row.title;
        this.jsTableData = [jsData]
        this.csTableData = [csData];
        this.textDataSources = formatToData(basic, '报警值');
      })
      this.recordVisible = true;
    },
    /** 查询信义大模型问答记录列表 */
    getList() {
      this.loading = true;
      const enumType = {
        '0': { color: 'tips_warning', label: '报警中' },
        '1': { color: 'tips_success', label: '用户关闭' },
        '2': { color: 'tips_close', label: '系统关闭' },
        '3': { color: 'tips_warning', label: '应急处理中' }
      }
      listWarn({ ...this.queryParams, type: 0 }).then(response => {
        this.recordList = response.rows.map(item => ({
          ...item,
          status: enumType[item.status].label
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sessionId: null,
        type: null,
        module: null,
        userId: null,
        showVal: null,
        question: null,
        answer: null,
        warningId: null,
        counts: null,
        isStrong: null,
        isSatisfied: null,
        isShutdown: null,
        delFlag: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加信义大模型问答记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改信义大模型问答记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        return delRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/record/export', {
        ...this.queryParams
      }, `record_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.waring-answer-wrapper {
  display: flex;
  justify-content: space-between;
  // align-items: flex-start;

  .message-inner {
    width: 210px;
    flex-shrink: 0;

    span {
      white-space: nowrap;
    }
  }

  .table-inner {
    width: 100%;
    padding-left: 20px;
    .warning-table {
      width: 100%;

      .title {
        margin-bottom: 8px;
        line-height: 16px;
        font-size: 12px;
        font-weight: bold;
        color: #1A2029;
      }
    }
  }
}

.radio-wrapper {

.radio-btn-group {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  text-align: center;
  color: #5E5E5E;

  .radio-btn {
    width: 62px;
    height: 28px;
    border-radius: 4px;
    background: #F4F6F8;
    font-size: 14px;
    line-height: 26px;
    cursor: pointer;

    &.active,
    &:hover {
      color: #2454FF;
      background: #E2F1FF;
    }

    &.active {
      background: #E2F1FF url('@/assets/images/chat/bg-raido-check.png') right bottom no-repeat;
    }
  }
}

}
</style>