<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;" @keyup.enter.native="queryList">
      <el-form-item label="遥测站编码">
        <el-input v-model="queryParams.stationCode" placeholder="遥测站编码" width="120px" maxlength="10" show-word-limit
          clearable />
      </el-form-item>

      <el-form-item label="问题类型">
        <el-select v-model="queryParams.queryParentId" class="filter-item" placeholder="问题类型" width="150px" clearable
          @change="markQuerySelectChange">
          <el-option v-for="item in state.dicMarkTypes" :key="item.markName" :label="item.markName" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="问题描述">
        <el-select v-model="queryParams.markId" class="filter-item" placeholder="请先选择问题类型" width="150px" clearable>
          <el-option v-for="item in state.querySelectMarkModel.childList" :key="item.markName" :label="item.markName"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="处理状态">
        <el-select v-model="queryParams.processResults" class="filter-item" placeholder="处理状态" width="150px" clearable>
          <el-option v-for="(key, value) in Dic.processResultsState" :key="key" :label="key" :value="value" />
        </el-select>
      </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%" :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 fit prop="stationCode" label="遥测站" header-align="center" width="110" />
      <el-table-column prop="stationName" label="遥测站名称" header-align="center" width="190" show-overflow-tooltip />
      <el-table-column prop="markParentName" label="问题类型" header-align="center" width="140" />
      <el-table-column prop="markTypeName" label="问题描述" header-align="center" width="140" />
      <el-table-column prop="markDescription" label="备注信息" header-align="center" width="140" />
      <el-table-column prop="createMan" label="登记人" header-align="center" width="110" />
      <el-table-column prop="createTime" label="登记时间" header-align="center" width="160" />
      <el-table-column prop="processResults" label="处理结果" header-align="center" width="100">
        <template #default="scope">
          <span>{{ Dic.processResultsState[scope.row.processResults] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="processTime" label="处理时间" header-align="center" width="160" />
      <el-table-column prop="processMan" label="处理人" header-align="center" width="100" />
      <el-table-column prop="reviewFlag" label="使用服务侧值" header-align="center" width="110">
        <template #default="scope">
          {{ scope.row.reviewFlag == '1' ? '是' : '否' }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="140">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)" :disabled="scope.row.processResults == '1'">编辑</el-button>
          <el-button type="text" @click="handleDeal(scope.row)" :disabled="scope.row.processResults == '1'">处理</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)"
            :disabled="scope.row.processResults == '1'">删除</el-button>
        </template>
      </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" :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="editdialog.title" v-model="editdialog.visible" width="450px" center>
      <el-form ref="editFormRef" :model="formEditData" label-width="100px" :rules="state.rules">
        <el-form-item label="遥测站编码:" prop="stationCode">
          <el-input v-model="formEditData.stationCode" placeholder="遥测站编码" style="width: 260px;" maxlength="10" show-word-limit
          clearable/>
        </el-form-item>
        <el-form-item label="问题类型:">
          <el-select v-model="formEditData.queryParentId" placeholder="问题类型" style="width: 260px;" @change="markEditSelectChange">
            <el-option v-for="item in state.dicMarkTypes" :key="item.markName" :label="item.markName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述:" prop="markId">
          <el-select v-model="formEditData.markId" class="filter-item" placeholder="请先选择问题类型" style="width: 260px;">
            <el-option v-for="item in editSelectMarkModel.childList" :key="item.markName" :label="item.markName"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息:">
          <el-input v-model="formEditData.markDescription" placeholder="备注信息" style="width: 260px;" />
        </el-form-item>
        <el-form-item label="使用服务侧值:">
          <el-checkbox v-model="formEditData.reviewFlag" true-label="1" false-label="0"></el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :disabled="state.saveDisabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="dealDialog.title" v-model="dealDialog.visible" width="450px" center>
      <el-form ref="dealFormRef" :model="formEditData" label-width="100px" :rules="state.dealRules">
        <el-form-item label="遥测站编码:" prop="stationCode">
          <el-input v-model="formEditData.stationCode" placeholder="遥测站编码" style="width: 260px;" disabled="true" />
        </el-form-item>
        <el-form-item label="问题类型:">
          <el-select v-model="formEditData.queryParentId" placeholder="问题类型" style="width: 260px;" @change="markEditSelectChange" disabled="true">
            <el-option v-for="item in state.dicMarkTypes" :key="item.markName" :label="item.markName" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="问题描述:" prop="markId">
          <el-select v-model="formEditData.markId" class="filter-item" placeholder="请先选择问题类型" style="width: 260px;">
            <el-option v-for="item in editSelectMarkModel.childList" :key="item.markName" :label="item.markName"
              :value="item.id" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="备注信息:">
          <el-input v-model="formEditData.markDescription" placeholder="备注信息" style="width: 260px;" disabled="true" />
        </el-form-item>
        <el-form-item label="处理结果:" prop="processResults">
          <el-select v-model="formEditData.processResults" class="filter-item" placeholder="问题描述" style="width: 260px;">
            <el-option v-for="(key, value) in Dic.processResultsState" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitDealForm" :disabled="state.saveDisabled">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import MarkRecordAction from "@/api/mark/markrecord";
import { TMarkRecordQueryParam, TMarkRecordModel, Dialog, PageResult, DicMarkTypeModel } from "@/types";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import DicMarkTypeAction from "@/api/mark/dicmarktype"
import Dic from "@/dictionary";

const editFormRef = ref(ElForm);
const dealFormRef = ref(ElForm);
let locale = ref(zhCn);
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';
const my_table = ref();
const loading = ref(false);
const state = reactive({
  queryParams: { page: 1, rows: 10 } as TMarkRecordQueryParam,
  currentType: 0,//val=0 新增; =1 编辑;
  total: 0,
  small: false,
  background: true,
  disabled: false,
  search_disabled: false,
  editdialog: {} as Dialog,
  formEditData: {} as TMarkRecordModel,
  tableData: [] as TMarkRecordModel[],
  dicMarkTypes: [] as DicMarkTypeModel[],
  rules: {
    stationCode: [
      { required: true, message: "遥测站编码不能为空", trigger: "blur" },
      { min: 10, max: 10, message: "遥测站编码长度不合法", trigger: "blur" },
    ],
    markId: [
      { required: true, message: "请选择问题描述", trigger: "blur" }
    ]
  },
  saveDisabled: false,
  querySelectMarkModel: {} as DicMarkTypeModel,
  editSelectMarkModel: {} as DicMarkTypeModel,
  dealDialog: {} as Dialog,
  dealRules: {
    processResults: [
      { required: true, message: "处理结果不能为空", trigger: "blur" }
    ]
  },
});

const {
  queryParams,
  editdialog,
  formEditData,
  tableData,
  dicMarkTypes,
  querySelectMarkModel: querySelectMarkMOdel,
  editSelectMarkModel,
  dealDialog
} = toRefs(state);

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

const currentRow = ref();

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

const handleAdd = () => {
  state.currentType = 0;
  state.formEditData = {} as TMarkRecordModel;
  state.editdialog = {
    title: "新增标记记录",
    visible: true,
    disabled: false,
  };
};

const handleEdit = (row: any) => {
  state.currentType = 1;
  state.formEditData = JSON.parse(JSON.stringify(row));
  state.editdialog = {
    title: "编辑标记记录",
    visible: true,
    disabled: false,
  };

  markEditSelectChange(state.formEditData.queryParentId);
};

const queryList = () => {
  loading.value = true;
  state.search_disabled = true;
  if (state.queryParams.stationCode) {
        state.queryParams.stationCode = state.queryParams.stationCode.padStart(10, '0');     //不足10位前面自动补0
      }
  MarkRecordAction.QueryTMarkRecordList(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<TMarkRecordModel[]>;
          state.tableData = pageData.list;
          state.total = pageData.total;
        } else {
          ElMessage.error(error);
        }
        loading.value = false;
        state.search_disabled = false;
      }
      else {
        state.search_disabled = false;
        loading.value = false;
      }
    })
    .catch((error) => {
      loading.value = false;
      state.search_disabled = false;
    });
  loading.value = false;
  state.search_disabled = false;
};

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

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


const handleDeal = (row: any) => {
  state.currentType = 2;
  state.formEditData = JSON.parse(JSON.stringify(row));
  state.dealDialog = {
    title: "站点标记处理",
    visible: true,
    disabled: false,
  };
};

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

  queryDicMarkType();
  queryList();
});

//显示参数配置
const queryDicMarkType = () => {
  DicMarkTypeAction.QueryDicMarkTypeList()
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          state.dicMarkTypes = res as DicMarkTypeModel[];
        } else {
          ElMessage.error(error);
        }
      }
    });
}

//查询控制,问题类型选择项改变时
const markQuerySelectChange = (val: number) => {
  let cur = state.dicMarkTypes.find(s => s.id == val);
  if (cur != null && cur != undefined) {
    state.querySelectMarkModel = cur;
    if (cur.childList.length > 0 && cur.childList.at(0) && cur.childList[0].id && state.queryParams.queryParentId) {
      state.queryParams.markId = cur.childList[0].id;
    }
  }
}

//编辑窗体(含新增),问题类型选择项改变时
const markEditSelectChange = (val: number) => {
  let cur = state.dicMarkTypes.find(s => s.id == val);
  if (cur != null && cur != undefined) {
    state.editSelectMarkModel = cur;
    if (cur.childList.length > 0 && cur.childList.at(0) && cur.childList[0].id && state.formEditData.markId) {
      state.formEditData.markId = cur.childList[0].id;
    }
  }
}

const submitEditForm = () => {
  editFormRef.value.validate((valid: any) => {
    if (valid) {
      let ax;
      if (state.currentType == 0) {
        state.formEditData.createMan = localStorage.getItem("UserName") || "";
        ax = MarkRecordAction.AddTMarkRecord(state.formEditData);
      } else {
        ax = MarkRecordAction.EditTMarkRecord(state.formEditData);
      }
      ax.then((result) => {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success("保存成功");
          cancel();
          queryList();
        }
        else {
          ElMessage.error(error || "未知异常...");
        }
      });
    }
  });
}

const submitDealForm = () => {
  dealFormRef.value.validate((valid: any) => {
    if (valid) {
      state.formEditData.processMan = localStorage.getItem("UserName") || "";
      MarkRecordAction.EditTMarkRecord(state.formEditData).then((result) => {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success("保存成功");
          cancel();
          queryList();
        }
        else {
          ElMessage.error(error || "未知异常...");
        }
      });
    }
  });
}

const cancel = () => {
  state.formEditData = {} as TMarkRecordModel;
  state.editdialog.visible = false;
  state.dealDialog.visible = false;
}

</script>

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

.big_box {
  width: 100%;
  height: 640px;
  display: flex;
  justify-content: space-between;
}

/* 设置大盒子的布局为flex布局 */
.left_box {
  width: 55%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.left_box_full {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right_box {
  width: 45%;
  height: 95%;
  border-radius: 5px 5px 0 0;
  border: 1px solid rgb(204, 204, 204);
  margin-left: 5px;
}

.right_box_header {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: left; //水平居中
  align-items: center; //垂直居中
}

.right_box_content {
  width: 100%;
  height: 40px;
  border-top: 1px solid rgb(204, 204, 204);
  //overflow-y: auto;
}
</style>