<template>
  <div>
    <div>
      <el-row :gutter="10">
        <el-col :span="14">
          <el-card>
            <template #header>
              <div class="card-header">
                <span style="font-size:20px;">批量配置任务列表</span>
                <el-button type="primary" style="margin-left: 10px;float: right;margin-top: -5px;"
                  @click="queryList">查询任务
                </el-button>
                <el-button type="primary" style="margin-left: 10px;float: right;margin-top: -5px;"
                  @click="handleAdd">新增任务
                </el-button>
              </div>
            </template>
            <div>
              <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%," ref="my_table"
                :height="tableHeight" highlight-current-row @current-change="handleCurrentRowChange" size="large"
                :header-cell-style="{ background: '#FF000000', color: '#000000' }">

                <el-table-column type="expand">
                  <template #default="props">
                    <div m="4">
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.stationCode != null">遥测站编码: {{
                        props.row.taskRemoteCfgModel.stationCode
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.ip1Port1 != null">通道1地址: {{
                        props.row.taskRemoteCfgModel.ip1Port1
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.ip2Port2 != null">通道2地址: {{
                        props.row.taskRemoteCfgModel.ip2Port2
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.ip3Port3 != null">通道3地址: {{
                        props.row.taskRemoteCfgModel.ip3Port3
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.ip4Port4 != null">通道4地址: {{
                        props.row.taskRemoteCfgModel.ip4Port4
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.domainNamePort != null">域名地址: {{
                        props.row.taskRemoteCfgModel.domainNamePort
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.sampleInterval != null">采样间隔: {{
                        props.row.taskRemoteCfgModel.sampleInterval
                      }} 分钟</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.upInterval != null">上传服务器间隔: {{
                        props.row.taskRemoteCfgModel.upInterval
                      }} 分钟</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.ltSampleInterval != null">低温采样间隔: {{
                        props.row.taskRemoteCfgModel.ltSampleInterval
                      }}
                        小时</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.digitNum != null">数字个数: {{
                        props.row.taskRemoteCfgModel.digitNum
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.wheelNum != null">字轮个数: {{
                        props.row.taskRemoteCfgModel.wheelNum
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.uintType != null">水表尾数单位: {{
                        global.getUnitType(props.row.taskRemoteCfgModel.uintType)
                      }}m³
                      </p>
                      <!-- 压力表专用配置 -->
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pgRangeMax != null">量程范围: {{
                        props.row.taskRemoteCfgModel.pgRangeMin
                      }}-- {{
  props.row.taskRemoteCfgModel.pgRangeMax
}}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pgPrecisionType != null">精度类型: {{
                        global.getpgPrecisionType(props.row.taskRemoteCfgModel.pgPrecisionType)
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pgCorrectvalue != null">校正参数: {{
                        props.row.taskRemoteCfgModel.pgCorrectvalue
                      }}</p>
                      <p m="t-0 b-2" v-if="!tool.stringIsNullOrEmpty(props.row.taskRemoteCfgModel.pgManualConfig)">
                        坐标点赋值: {{
                          props.row.taskRemoteCfgModel.pgManualConfigCol
                        }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pgIsDebug != null">图片是否描点: {{
                        props.row.taskRemoteCfgModel.pgIsDebug == '1' ? '是' :
                          '否'
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pgInitTargetRegion != null">目标历史初始化: {{
                        props.row.taskRemoteCfgModel.pgInitTargetRegion == '1' ?
                          '是' : '否'
                      }}</p>
                      <!-- 压力表专用配置 -->

                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.networkRegTimeout != null">入网超时时间(秒): {{
                        props.row.taskRemoteCfgModel.networkRegTimeout
                      }} 秒</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.tongxunWay != null">数传类型: {{
                        props.row.taskRemoteCfgModel.tongxunWay == '2' ? 'NB' :
                          'CAT1'
                      }}
                      </p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.tianxianType != null">天线类型:
                        {{ Dic.tianxianType[props.row.taskRemoteCfgModel.tianxianType] }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.lastVal != null">当前读数: {{
                        props.row.taskRemoteCfgModel.lastVal
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.dnType != null">水表口径: {{
                        global.getDnType(props.row.taskRemoteCfgModel.dnType)
                      }} </p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.setupDir != null">安装方向: {{
                        Dic.setupDirMap[props.row.taskRemoteCfgModel.setupDir].label
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.setupYear != null">安装年份: {{
                        props.row.taskRemoteCfgModel.setupYear
                      }} 年</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.workLt != null">工作温度范围: {{
                        props.row.taskRemoteCfgModel.workLt
                      }} -- {{
  props.row.taskRemoteCfgModel.workHt
}}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.batAlarmVt != null">低电压报警值: {{
                        props.row.taskRemoteCfgModel.batAlarmVt
                      }} V</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.batAlarmSoc != null">余电报警电量: {{
                        props.row.taskRemoteCfgModel.batAlarmSoc
                      }} %</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.aiPullBack != null">强制拉回概率: {{
                        props.row.taskRemoteCfgModel.aiPullBack
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.aiPass != null">识别概率阈值: {{
                        props.row.taskRemoteCfgModel.aiPass
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.aiSinglePass != null">位概率阀值: {{
                        props.row.taskRemoteCfgModel.aiSinglePass
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pwmHz != null">背光频率: {{
                        props.row.taskRemoteCfgModel.pwmHz
                      }} HZ</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.pwmDuty != null">背光占空比: {{
                        props.row.taskRemoteCfgModel.pwmDuty
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.flashBrightMin != null">补光灯亮度范围: {{
                        props.row.taskRemoteCfgModel.flashBrightMin
                      }} --
                        {{ props.row.taskRemoteCfgModel.flashBrightMax }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.cpuVersion != null">CPU版本: {{
                        props.row.taskRemoteCfgModel.cpuVersion
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.tongxunVersion != null">通讯版本: {{
                        props.row.taskRemoteCfgModel.tongxunVersion
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.upWholeImgWeekRule != null">大图上传周规则: {{
                        global.jxweekString(props.row.taskRemoteCfgModel.upWholeImgWeekRule)
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.wiTaskManwakeupFlag != null">手动触发传大图: {{
                        props.row.taskRemoteCfgModel.wiTaskManwakeupFlag == '1' ? '是' : '否'
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.wiTaskMonthFlag != null">月初月末传大图: {{
                        props.row.taskRemoteCfgModel.wiTaskMonthFlag ==
                          '1' ? '是' : '否'
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.wiTaskSpecdateFlag != null">
                        指定日期发大图:{{ global.getWiTaskSpecdateTip(props.row.taskRemoteCfgModel, 0) }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.logUploadRules != null">日志上传规则:
                        {{ global.getLogUploadRulesTip(props.row.taskRemoteCfgModel, 0) }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.isprintcomlog != null">输出串口日志: {{
                        props.row.taskRemoteCfgModel.isprintcomlog == '1' ?
                          '是' : '否'
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.uploadLastFailLogFlag != null">上传上一次MCU通讯错误的日志:
                        {{
                          props.row.taskRemoteCfgModel.uploadLastFailLogFlag == '1' ? '是' : '否'
                        }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.logTaskManwakeupFlag != null">手动触发发送本次工作日志: {{
                        props.row.taskRemoteCfgModel.logTaskManwakeupFlag == '1' ? '是' : '否'
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.isresetbat === '1'">电池使用时长清零: 是</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.isrestmcu === '1'">MCU运行次数清零: 是</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.isresetwdt === '1'">WDT读数清零: 是</p>

                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.imageType != null">上传图片类型: {{
                        props.row.taskRemoteCfgModel.imageType
                      }} </p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.imageMargin != null">图片外扩像素: {{
                        props.row.taskRemoteCfgModel.imageMargin
                      }} </p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.imageConfig != null">指定数字区域: {{
                        global.getImageConfigip(props.row.taskRemoteCfgModel)
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.uploadCnnFlag != null">上传模型输出结果: {{
                        props.row.taskRemoteCfgModel.uploadCnnFlag == '1'
                          ? '是' :
                          '否'
                      }}</p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.nmsThreshold != null">NMS阈值: {{
                        props.row.taskRemoteCfgModel.nmsThreshold
                      }} </p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.regionImageType != null">区域上报图片类型: {{
                        props.row.regionImageType == '1' ?
                          'JPG'
                          : 'BMP'
                      }} </p>
                      <p m="t-0 b-2" v-if="props.row.taskRemoteCfgModel.jpgCompressType != null">JPG的压缩类型: {{ props.row.jpgCompressType }}
                      </p>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column type="index" width="50" align="center" />
                <el-table-column prop="taskDescribe" label="任务描述" header-align="center" min-width="200"
                  show-overflow-tooltip />
                <el-table-column label="任务类型" header-align="center" width="85">
                  <template #default="scope">
                    <span>{{ taskDic.taskBatchType[scope.row.taskType] }}</span>
                  </template>
                </el-table-column>

                <el-table-column prop="executionTime" label="计划创建时间" header-align="center" width="110">
                  <template #default="scope">
                    {{ tool.dateFormatYMDHm(scope.row.executionTime) }}
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="minutesAhead" label="提前分钟" header-align="center" width="80" /> -->

                <el-table-column label="执行状态" header-align="center" width="80">
                  <template #default="scope">
                    <el-tag :type="finishedStatusType[scope.row.finishedFlag]" effect='dark'>{{
                      taskDic.taskBatchState[scope.row.finishedFlag]
                    }}
                    </el-tag>
                    <!-- <span :type="deviceTypeColorMap[scope.row.deviceType]">{{taskDic.taskBatchState[scope.row.finishedFlag]}}</span> -->
                  </template>
                </el-table-column>

                <el-table-column prop="finishedTime" label="更新时间" header-align="center" width="100">
                  <template #default="scope">
                    {{ tool.dateFormatYMDHm(scope.row.finishedTime) }}
                  </template>
                </el-table-column>

                <el-table-column prop="createMan" label="创建人" header-align="center" width="80" />
                <el-table-column prop="createTime" label="创建时间" header-align="center" width="100">
                  <template #default="scope">
                    {{ tool.dateFormatYMDHm(scope.row.createTime) }}
                  </template>
                </el-table-column>

                <el-table-column label="操作" align="center" width="100">
                  <template #default="scope">
                    <el-button type="text" @click="handleEdit(scope.row)" :disabled="scope.row.finishedFlag !== '0'">编辑
                    </el-button>
                    <el-button type="text" @click="handleDelete(scope.row)" :disabled="scope.row.finishedFlag !== '0'">
                      删除
                    </el-button>
                  </template>
                </el-table-column>

                <el-table-column prop="memo" label="备注信息" header-align="center" width="150"></el-table-column>
              </el-table>
              <el-config-provider :locale="locale">
                <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
                  :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
                  @size-change="handleSizeChange" @current-change="handleCurrentChange" :background="state.background"
                  layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                  style="text-align: center;height: 20px;margin-top: 7px;" />
              </el-config-provider>
            </div>
          </el-card>
        </el-col>
        <el-col :span="10">
          <el-card>
            <template #header>
              <div class="card-header">
                <span style="font-size:20px;">任务明细[{{ state.detailData == null ? 0 : state.detailData.length }}]</span>
              </div>
            </template>
            <div>
              <el-table v-loading="loading" :data="state.detailData" border stripe style="width: 100%,"
                :height="detailTableHeight" highlight-current-row
                :header-cell-style="{ background: '#FF000000', color: '#000000' }">
                <el-table-column type="index" width="50" align="center" />
                <!-- <el-table-column prop="deviceSn" label="设备SN" header-align="center" width="110" /> -->
                <el-table-column prop="deviceSn" label="设备SN" header-align="center" width="110">
                  <template #default="scope">
                    <span style="color:blue;cursor:pointer;text-decoration: underline;" title="点击查看配置"
                      @click="showDevCfg(scope.row)">{{ scope.row.deviceSn }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="stationCode" label="遥测站编码" header-align="center" width="100" />
                <el-table-column prop="stationName" label="遥测站名称" header-align="center" width="150" />

                <el-table-column label="完成状态" header-align="center" align="center" width="100">
                  <template #default="scope">
                    <span v-if="scope.row.finishedFlag === '0'">未执行</span>
                    <span v-if="scope.row.finishedFlag === '1'">已完成</span>
                  </template>
                </el-table-column>

                <el-table-column prop="finishedTime" label="完成时间" header-align="center" width="100">
                  <template #default="scope">
                    {{ tool.dateFormatYMDHm(scope.row.finishedTime) }}
                  </template>
                </el-table-column>
                <!-- <el-table-column label="操作" width="60">
                  <template #default="scope">
                    <el-button type="text" @click="handleDelete(scope.row)"
                      :disabled="scope.row.finishedFlag==='1'||scope.row.finishedFlag==='2'">删除</el-button>
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog :title="taskDialog.title" v-model="taskDialog.visible" width="1300px" height="200px" draggable center
      @close="dialogClose">
      <!-- 使用v-if强制重新渲染 v-if="adddialog.visible" -->
      <batchForm :data="state.formEditData" :isAdd="state.isAdd" :task-type="state.taskType" v-if="taskDialog.visible"
        @change="childMethod">
      </batchForm>
    </el-dialog>

    <el-dialog :title="cfgdialog.title" v-model="cfgdialog.visible" width="1100px" center>
      <DevCfgDialog :stationCode="state.cfgData.stationCode" :deviceSn="state.cfgData.deviceSn"
        v-if="cfgdialog.visible"></DevCfgDialog>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import TaskBatchRemoteAction from "@/api/taskbatch/taskbatchremote";
import { TaskBatchRemoteQueryParam, TaskBatchRemoteModel, Dialog, PageResult, TaskBatchRemoteDetailModel, TaskRemoteCfg } from '@/types';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import tool from '@/until/tool';
import taskDic from '@/dictionary';
import Dic from '@/dictionary/aicbqcfg';
import global from '@/until/global';
import batchForm from '@/components/batchcfg/index.vue';
import DevCfgDialog from "@/components/devcfg/index.vue";
import { Message, MessageBox } from "@element-plus/icons-vue";


let locale = ref(zhCn);
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';

const table = ref(ElTable);
const loading = ref(false)
const my_table = ref();
const state = reactive({
  currentType: 0,
  total: 0,
  small: false,
  background: true,
  disabled: false,
  queryParams: { unitName: '', page: 1, rows: 10 } as TaskBatchRemoteQueryParam,
  pagination: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },
  tableData: [] as TaskBatchRemoteModel[],
  detailData: [] as TaskBatchRemoteDetailModel[],
  formEditData: {} as TaskBatchRemoteModel,
  taskDialog: {} as Dialog,
  isAdd: true,
  taskType: 9,
  cfgdialog: {} as Dialog,
  cfgData: {} as TaskBatchRemoteDetailModel
});

type mapStatee = Record<string, string>;
const finishedStatusType: mapStatee = {
  0: '',
  1: 'warning',
  2: 'success',
};

const {
  queryParams,
  tableData,
  taskDialog,
  formEditData,
  isAdd,
  taskType,
  cfgdialog
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 210);
const detailTableHeight = ref(document.documentElement.clientHeight - 180);
const currentRow = ref()

const handleCurrentRowChange = (val: TaskBatchRemoteModel | undefined) => {
  currentRow.value = val;

  if (val) {
    state.detailData = val.detailModels;
  }
}

const queryList = () => {
  loading.value = true;
  if (!adminFlag) {
    state.queryParams.createMan = localStorage.getItem("UserName") || "";
  } else {
  }
  TaskBatchRemoteAction.QueryTaskBatchRemoteList(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<TaskBatchRemoteModel[]>;
          state.tableData = pageData.list;
          state.total = pageData.total;
          if (pageData.list.length > 0) {
            state.detailData = pageData.list[0].detailModels;
          } else {
            state.detailData = [];
          }
        } else {
          ElMessage.error(error || "未知异常...");
        }
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error);
    });
  loading.value = false;
};

const handleAdd = () => {
  state.isAdd = true;
  state.taskType = 9;
  state.taskDialog = {
    title: "新增批量任务",
    visible: true,
    disabled: false,
  };
}

const handleEdit = (row: any) => {
  state.currentType = 3;
  state.formEditData = JSON.parse(JSON.stringify(row));

  state.taskDialog = {
    title: "编辑批量任务",
    visible: true,
    disabled: false,
  };

  state.isAdd = false;
};

const handleDelete = (row: TaskBatchRemoteModel) => {
  ElMessageBox.confirm(" 是否删除任务[" + row.taskDescribe + "]? ", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
    center: true,
  })
    .then(() => {
      TaskBatchRemoteAction.DeleteTaskBatchRemote(row.id).then((result) => {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success("删除成功");
          queryList();
        } else {
          ElMessage.success(error || "未知异常...");
        }
      });
    }).then(() => {
      queryList();
    }).catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除成功!",
      });
    });
};

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
  if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
};

function findInput(container: any) {
  let nextEl = container.nextElementSibling;
  if (!nextEl) return;
  let input = nextEl.querySelector("input");
  while (input.id === "el-select") {
    nextEl = nextEl.nextElementSibling;
    if (!nextEl) return;
    input = nextEl.querySelector("input");
  }
  if (input.className.includes("el-input__inner")) return input;
}

const dialogClose = () => {
  state.taskDialog = {
    title: "",
    visible: false,
    disabled: true,
  };
  state.formEditData = {} as TaskBatchRemoteModel;
}

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 210;
    detailTableHeight.value = document.documentElement.clientHeight - 180;
  }
  queryList();
})

//子组件保存或取消的返回值
const childMethod = (val: Boolean) => {
  dialogClose();
  if (val) {
    queryList();
  }
}

//显示参数配置
const showDevCfg = (row: any) => {
  state.cfgData = row as TaskBatchRemoteDetailModel;

  state.cfgdialog = {
    title: "设备参数预览[" + state.cfgData.deviceSn + "]",
    visible: true,
    disabled: false,
  };
}
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}

::v-deep .el-transfer-panel {
  width: 400px;
  height: 750px;
}

::v-deep .el-table__body tr.current-row>td {
  color: #fff;
  background: #6db3fa !important;
}
</style>