<template>
  <!-- <div class="title">召测配置页面</div> -->
  <el-form ref="queryFormRef" :model="queryParams" :inline="true" @keyup.enter.native="queryList"
    style="margin-bottom: -10px;">
    <el-form-item label="设备SN:" style="margin-left: 5px;width: 240px;">
      <el-input v-model="queryParams.deviceSn" placeholder="设备SN" size="small" maxlength="11" clearable
        show-word-limit />
    </el-form-item>
    <el-form-item label="遥测站编码:" style="margin-left: 10px;width: 245px;">
      <el-input v-model="queryParams.stationCode" placeholder="遥测站编码" size="small" maxlength="10" clearable
        show-word-limit />
    </el-form-item>

    <el-form-item label="任务类型:" style="margin-left: 10px;width: 180px;">
      <el-select v-model="queryParams.taskType" class="filter-item" placeholder="任务类型" size="small" clearable
        style="max-width: 150px;">
        <!-- <el-option v-for="(key, value) in taskTypeQueryMap" :key="key" :label="key" :value="value" /> -->
        <el-option v-for="item in taskTypeQueryMap2" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="任务等级:" style="margin-left: 10px;width: 180px;">
      <el-select v-model="queryParams.taskLevel" class="filter-item" placeholder="任务等级" size="small" clearable>
        <el-option v-for="item in taskLevelsQuery" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>

    <el-form-item label="创建日期:" style="margin-left: 10px;">
      <el-config-provider :locale="locale">
        <el-date-picker v-model="queryParams.createTimeStart" type="date" placeholder="开始日期" :shortcuts="shortcuts"
          value-format="YYYY-MM-DD 00:00:00" size="small" style="max-width: 130px;" />
      </el-config-provider>
    </el-form-item>

    <el-form-item>
      <el-config-provider :locale="locale">
        <el-date-picker v-model="queryParams.createTimeEnd" type="date" placeholder="结束日期" :shortcuts="shortcuts"
          value-format="YYYY-MM-DD 23:59:59" size="small" style="max-width: 130px;" />
      </el-config-provider>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" class="button" :disabled="state.search_disabled" @click="queryList">
        查询任务
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" class="button" @click="handleAdd">新增任务</el-button>
    </el-form-item>
  </el-form>

  <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%;margin-top: -10px;"
    :height="tableHeight" highlight-current-row @current-change="handleCurrentRowChange" ref="my_table"
    :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
    <el-table-column fixed type="index" width="50" align="center" />
    <el-table-column fixed prop="deviceSn" label="设备SN" header-align="center" width="120" />
    <!-- <el-table-column prop="deviceName" label="设备名称" header-align="center" width="100" /> -->
    <el-table-column fit prop="stationCode" label="遥测站编码" header-align="center" width="100" />
    <el-table-column label="任务类型" header-align="center" width="100" align="center">
      <template #default="scope">
        <span>{{ taskTypeQueryMap2.find((s) => s.value == scope.row.taskType)?.label }}</span>
      </template>
    </el-table-column>

    <el-table-column label="任务等级" header-align="center" width="100" align="center">
      <template #default="scope">
        <span>{{ taskLevels.find((s) => s.value == scope.row.taskLevel)?.label }}</span>
        <!-- <span v-if="scope.row.taskLevel === 1">常规任务</span>
        <span v-if="scope.row.taskLevel === 2">普通任务</span>
        <span v-if="scope.row.taskLevel === 3">紧急任务</span>
        <span v-if="scope.row.taskLevel === 99">特权任务</span> -->
      </template>
    </el-table-column>

    <el-table-column prop="createMan" label="创建人" header-align="center" width="100" align="center" />
    <el-table-column prop="createTime" label="创建时间" header-align="center" width="160" />

    <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="160" />

    <el-table-column label="" align="left" width="150">
      <template #default="scope">
        <el-button type="text" @click="handleEdit(scope.row)"
          :disabled="scope.row.finishedFlag === '1' || scope.row.createMan === '批量任务'">编辑</el-button>
        <el-button type="text" @click="submitDeleteForm(scope.row)"
          :disabled="scope.row.finishedFlag === '1' || scope.row.createMan === '批量任务'">删除</el-button>
      </template>
    </el-table-column>
    <el-table-column fixed="right" />
  </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" :background="state.background"
      layout="total, sizes, prev, pager, next, jumper" :total="state.total"
      style="text-align: center; margin-top: 10px; height: 30px" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </el-config-provider>

  <el-dialog :title="adddialog.title" v-model="adddialog.visible" width="450px" draggable center @close="dialogClose">
    <el-form ref="addFormRef" :model="formAddData" :rules="state.rules" label-width="120px">
      <el-form-item label="设备SN:" prop="deviceSn" style="width: 337px;">
        <el-input v-model="formAddData.deviceSn" placeholder="设备SN" width="120px" maxlength="11" show-word-limit />
      </el-form-item>
      <el-form-item label="任务类型:" prop="taskType">
        <el-select v-model="formAddData.taskType" class="filter-item" placeholder="任务类型">
          <el-option v-for="(key, value) in taskTypeMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务等级:" prop="taskType">
        <el-select v-model="formAddData.taskLevel" class="filter-item" placeholder="任务等级" prop="taskLevel">
          <el-option v-for="item in taskLevels" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(0)">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog :title="editdialog.title" v-model="editdialog.visible" width="450px" draggable center>
    <el-form ref="editFormRef" :model="formEditData" label-width="100px">
      <el-form-item label="设备SN:">
        <el-input v-model="formEditData.deviceSn" placeholder="设备SN" width="120px" />
      </el-form-item>
      <el-form-item label="任务类型:">
        <el-select v-model="formEditData.taskType" class="filter-item" placeholder="任务类型" width="120px">
          <el-option v-for="(key, value) in taskTypeMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务等级:">
        <el-select v-model="formEditData.taskLevel" class="filter-item" placeholder="任务等级" width="120px">
          <el-option v-for="item in taskLevels" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel(1)">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import TTaskDownAction from "@/api/downlinktask/ttaskdown";
import { TTaskDownQueryParam, TTaskDown, Dialog, PageResult } from "@/types";
import zhCn from "element-plus/lib/locale/lang/zh-cn";

let locale = ref(zhCn);
let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;

const addFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

const loading = ref(false);
const my_table = ref();
const state = reactive({
  queryParams: { page: 1, rows: pageSize } as TTaskDownQueryParam,
  total: 0,
  small: false,
  background: true,
  disabled: false,
  search_disabled: false,
  adddialog: {} as Dialog,
  editdialog: {} as Dialog,
  formAddData: {} as TTaskDown,
  formEditData: {} as TTaskDown,
  tableData: [] as TTaskDown[],
  rules: {
    deviceSn: [
      { required: true, message: "设备SN不能为空", trigger: "blur" },
      { min: 11, max: 11, message: "设备SN长度不合法", trigger: "blur" },
    ],
    taskType: [
      { required: true, message: "任务类型不能为空", trigger: "blur" },
    ],
    taskLevel: [
      { required: true, message: "任务等级不能为空", trigger: "blur" },
    ],
  },
});

const {
  queryParams,
  total,
  adddialog,
  editdialog,
  formAddData,
  formEditData,
  tableData,
} = toRefs(state);

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

const currentRow = ref();

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

//任务类型
const taskTypeMap = {
  // '1': "审核结果",
  '2': "远程配置",
  '3': "召测配置",
  //'4': "召测数据",
};

// const taskTypeQueryMap = {
//   '1': "审核结果",
//   '2': "远程配置",
//   '3': "召测配置",
//   '4': "召测数据",
//   '0': "全部",
// };

const taskTypeQueryMap2 = [
  { value: 1, label: '审核结果' },
  { value: 2, label: '远程配置' },
  { value: 3, label: '召测配置' },
  { value: 4, label: '召测数据' },
  { value: 0, label: '全部' },
];


/* const taskLevelMap = {
  1: "常规任务",
  2: "普通任务",
  3: "紧急任务",
  99: "特权任务",
};
 */
//任务等级
const taskLevels = [
  {
    value: 1,
    label: '常规任务',
  },
  {
    value: 2,
    label: '普通任务',
  },
  {
    value: 3,
    label: '紧急任务',
  },
  {
    value: 99,
    label: '特权任务',
  },
]

//任务等级
const taskLevelsQuery = [
  {
    value: 1,
    label: '常规任务',
  },
  {
    value: 2,
    label: '普通任务',
  },
  {
    value: 3,
    label: '紧急任务',
  },
  {
    value: 99,
    label: '特权任务',
  },
  {
    value: 0,
    label: '全部',
  },
]

const handleAdd = () => {
  state.formAddData = {} as TTaskDown;
  state.formAddData.taskType = '3';
  state.formAddData.taskLevel = 1;
  state.adddialog = {
    title: "新增召测任务",
    visible: true,
    disabled: false,
  };
};

const handleEdit = (row: any) => {
  state.formEditData = row;
  state.editdialog = {
    title: "编辑召测任务",
    visible: true,
    disabled: false,
  };
};

const queryList = () => {
  loading.value = true;
  state.search_disabled = true;

  if (state.queryParams.stationCode) {
    state.queryParams.stationCode = state.queryParams.stationCode.padStart(10, '0');     //不足10位前面自动补0
  }

  if (state.queryParams.deviceSn) {
    state.queryParams.deviceSn = state.queryParams.deviceSn.padStart(11, '0');     //不足10位前面自动补0
  }

  TTaskDownAction.QueryTTaskDownList(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag != undefined && flag == 1) {
          const pageData = res as PageResult<TTaskDown[]>;
          state.tableData = pageData.list;
          state.total = pageData.total;
        } else {
        }
        loading.value = false;
        state.search_disabled = false;
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error);
      loading.value = false;
      state.search_disabled = false;
    });
};

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
  localStorage.setItem("PageSize", val.toString());
};

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; } }
};

const submitAddForm = () => {
  addFormRef.value.validate((valid: any) => {
    if (valid) {
      state.formAddData.createMan = localStorage.getItem("UserName") + "";
      TTaskDownAction.AddTTaskDown(state.formAddData).then((result) => {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success("新增成功");
          cancel(0);
          queryList();
        }
        else {
          ElMessage.warning(error);
        }
      });
    }
  });
};

const submitEditForm = () => {
  TTaskDownAction.EditTTaskDown(state.formEditData).then((result) => {
    ElMessage.success("编辑成功");
    cancel(1);
    queryList();
  });
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(" 是否删除设备[" + row.deviceSn + "]? ", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
    center: true,
  })
    .then(() => {
      TTaskDownAction.DeleteTTaskDown(row.id).then((result) => {
        ElMessage.success("删除成功");
        queryList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除成功!",
      });
    });
};

const cancel = (dialogType: number) => {
  if (dialogType == 0) {
    //addFormRef.value.resetFields();
    state.formAddData = {} as TTaskDown;
    state.formEditData = {} as TTaskDown;
    state.adddialog.visible = false;
  } else {
    //editFormRef.value.resetFields();
    state.formAddData = {} as TTaskDown;
    state.formEditData = {} as TTaskDown;
    state.editdialog.visible = false;
  }
};

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

  queryList();
});

/* 日期控件开始 */
const size = ref<'' | 'large' | 'small'>('')
const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    },
  },
  {
    text: '前一周',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    },
  },
]
/* 日期控件结束 */

const dialogClose = () => {
  state.formAddData = {} as TTaskDown;
  state.formEditData = {} as TTaskDown;
}
</script>

<style lang="scss" scoped>
.title {
  font-size: 30px;
}
</style>