<template>
  <div>
    <div class="titleBox">
      <div class="title">系统分析模型</div>
      <div class="btnBox">
        <el-button type="primary" @click="addJob()">
          <el-icon><CirclePlus /></el-icon>
          <span>新增</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="模型名称">
          <el-input
            placeholder="请输入模型名称"
            v-model="listQuery.mxmc"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleFilter"> 查询 </el-button>
          <el-button @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tabBox">
      <el-table
        :data="tableData"
        border
        :height="tableHeight"
        style="width: 100%"
        :key="keyCount"
      >
        <el-table-column
          sortable
          prop="id"
          show-overflow-tooltip
          label="模型编号"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="mxmc"
          show-overflow-tooltip
          label="模型名称"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="mxsm"
          show-overflow-tooltip
          label="模型说明"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="yxcs"
          show-overflow-tooltip
          label="运行次数"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="yjCs"
          show-overflow-tooltip
          label="预警次数"
        >
        </el-table-column>
        <el-table-column sortable label="模型状态" width="100px">
          <template #default="{ row }">
            <div>
              <el-tag size="small" type="success" v-if="row.mxzt == '01'"
                >运行中</el-tag
              >
              <el-tag size="small" type="danger" v-else-if="row.mxzt == '02'"
                >已停止</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template #default="{ row }">
            <template v-if="row.mxzt == '01'">
              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                icon-color="red"
                title="确定要停止?"
                @confirm="startModel(row)"
              >
                <template #reference>
                  <el-button size="small">停止</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                icon-color="red"
                title="确定要启动?"
                @confirm="stopModel(row)"
              >
                <template #reference>
                  <el-button size="small">启动</el-button>
                </template>
              </el-popconfirm>
            </template>

            <el-button @click="csSet(row)" size="small">参数设置</el-button>
            <el-button @click="updateJob(row)" size="small">修改</el-button>
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              title="确定要删除?"
              @confirm="delRole(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="fenye" :style="{ top: tableHeight + 'px' }">
        <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ isEdit ? "修改" : "新增" }}</span>
        <div>
          <!-- 修改 -->
          <el-button
            v-if="isEdit"
            type="primary"
            size="small"
            @click="onSave"
            :loading="buttonLoading"
            >保存</el-button
          >
          <!-- 新增 -->
          <el-button
            v-else
            type="primary"
            size="small"
            @click="onAdd"
            :loading="buttonLoading"
            >保存</el-button
          >
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </div>
      </div>
      <el-form
        ref="elform"
        class="mosty-from-wrap"
        :rules="rules"
        :inline="true"
        label-position="top"
        :model="dialogForm"
      >
      <el-form-item
          class="one"
          prop="id"
          label="模型编号"
          label-width="140px"
        >
          <el-input
            v-model="dialogForm.id"
            placeholder="请输入模型编号"
          ></el-input>
        </el-form-item>
        <el-form-item
          class="one"
          prop="ssbmid"
          label="所属辖区"
          label-width="140px"
        >
          <MOSTY.Department
            placeholder="请选择所属辖区"
            width="100%"
            clearable
            filterable
            v-model="dialogForm.ssbmid"
          />
        </el-form-item>
        <el-form-item
          class="one"
          prop="mxmc"
          label="模型名称"
          label-width="140px"
        >
          <el-input
            v-model="dialogForm.mxmc"
            placeholder="请输入模型名称"
          ></el-input>
        </el-form-item>
        <el-form-item class="one" prop="mxlx" label="模型类型">
          <el-select
            style="width: 100%"
            v-model="dialogForm.mxlx"
            placeholder="请选择模型类型"
          >
            <el-option label="街面违法犯罪预警" :value="'01'"></el-option>
            <el-option label="重点巡防区域预警" :value="'02'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          class="one"
          prop="mxsm"
          label="模型说明"
          label-width="140px"
        >
          <el-input
            v-model="dialogForm.mxsm"
            autocomplete="off"
            show-word-limit
            maxlength="3000"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 模型参数 -->
    <div v-if="dialogCSSZTableVisible" class="dialog">
      <div class="head_box">
        <span class="title">参数设置</span>
        <div>
          <el-button size="small" @click="dialogCSSZTableVisible = false"
            >关闭</el-button
          >
        </div>
      </div>
      <div class="mxcs_table">
        <div class="csmxadd">
          <el-button type="primary" @click="addCsModel()">
            <el-icon><CirclePlus /></el-icon>
            <span>新增</span>
          </el-button>
        </div>
        <el-table
          :data="tableCSData"
          border
          :height="tableHeight"
          style="width: 100%"
          :key="keyCount"
        >
          <el-table-column
            sortable
            prop="cslx"
            show-overflow-toolt
            label="参数类型"
          >
            <template #default="{ row }">
                <span>{{row.cslx == '01' ? '时间（分）':row.cslx == '02' ? '次数':row.cslx == '03' ? '人数':'距离（米）'}}</span>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="csmc"
            show-overflow-tooltip
            label="参数名"
          >
          </el-table-column>
          <el-table-column
            sortable
            prop="csz"
            show-overflow-tooltip
            label="参数值"
          >
          </el-table-column>
          <el-table-column
            sortable
            prop="csdm"
            show-overflow-tooltip
            label="参数代码"
          >
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="140">
            <template #default="{ row }">
              <el-button @click="updateCs(row)" size="small">修改</el-button>
              <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                icon-color="red"
                title="确定要删除?"
                @confirm="deleteCs(row)"
              >
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="fenye" :style="{ top: tableHeight + 'px' }">
          <el-pagination
            class="pagination"
            @size-change="handleSizeChangecs"
            @current-change="handleCurrentChangecs"
            :current-page="csform.pageCurrent"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="csform.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="cstotal"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 模型参数新增 修改 -->
    <div v-if="dialogcsFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ iscsEdit ? "修改" : "新增" }}</span>
        <div>
          <!-- 修改 -->
          <el-button
            v-if="iscsEdit"
            type="primary"
            size="small"
            @click="updateCsModel"
            :loading="buttonLoading"
            >保存</el-button
          >
          <!-- 新增 -->
          <el-button
            v-else
            type="primary"
            size="small"
            @click="saveCs"
            :loading="buttonLoading"
            >保存</el-button
          >
          <el-button size="small" @click="dialogcsFormVisible = false"
            >关闭</el-button
          >
        </div>
      </div>
      <el-form
        ref="elcsform"
        class="mosty-from-wrap"
        :rules="rules"
        :inline="true"
        label-position="top"
        :model="csform"
      >
        <el-form-item
          class="one"
          prop="csmc"
          label="参数名称"
          label-width="140px"
        >
          <el-input
            v-model="csform.csmc"
            placeholder="请输入参数名称"
          ></el-input>
        </el-form-item>
        <el-form-item class="one" prop="csz" label="参数值" label-width="140px">
          <el-input v-model="csform.csz" placeholder="请输入参数值"></el-input>
        </el-form-item>
        <el-form-item class="one" prop="csdm" label="参数代码" label-width="140px">
          <el-input v-model="csform.csdm" placeholder="请输入参数代码"></el-input>
        </el-form-item>
        <el-form-item class="one" prop="cslx" label="参数类型">
          <el-select
            style="width: 100%"
            v-model="csform.cslx"
            placeholder="请选择参数类型"
          >
            <el-option
              v-for="item in cslxList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from "vue";
import {
  getYJModelList,
  addYJmodel,
  putYJmodel,
  delYJModel,
  getCsList,
  addCs,
  putCs,
  delCs,
  getCsDTQZ
} from "@/api/basicsmanage/yjmodel";
const { proxy } = getCurrentInstance();
const searchBox = ref(null); // 搜索盒子
const keyCount = ref(0); //tabel组件刷新值
const tableHeight = ref(); // 表格高度
//查询参数
const total = ref(0);
const page = ref(1);
const size = ref(20);
const buttonLoading = ref(false);
const currentRow = ref({});
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10,
  mxmc: ""
});
const elform = ref(null);
const elcsform = ref(null);
//验证
const rules = ref({
  ssbmid: [{ required: true, message: "请选择所属辖区", trigger: "change" }],
  mxmc: [{ required: true, message: "请输入模型名称", trigger: "change" }],
  mxlx: [{ required: true, message: "请选择模型类型", trigger: "change" }],
  mxsm: [{ required: true, message: "请输入模型说明", trigger: "change" }],
  csmc: [{ required: true, message: "请输入参数名称", trigger: "change" }],
  csz: [{ required: true, message: "请输入参数值", trigger: "change" }],
  cslx: [{ required: true, message: "请选择参数类型", trigger: "change" }],
  id: [{ required: true, message: "请输入模型编号", trigger: "change" }],
  csdm: [{required: true, message: "请输入参数代码", trigger: "change"}]
});
// 参数类型
const cslxList = ref([
  {
    label: "时间(分)",
    value: "01"
  },
  {
    label: "次数",
    value: "02"
  },
  {
    label: "人数",
    value: "03"
  },
  {
    label: "距离（米）",
    value: "04"
  }
]);
// 参数设置
const csform = ref({});
const csparams = ref({
  pageSize: 10,
  pageCurrent: 1,
  mxid: ""
});
const cstotal = ref(0);
const iscsEdit = ref(false);
const tableCSData = ref([]);
const dialogCSSZTableVisible = ref(false);
const dialogcsFormVisible = ref(false);
function csSet(row) {
  csparams.value.mxid = row.id;
  dialogCSSZTableVisible.value = true;
  searchCs();
}
// 参数查询
function searchCs() {
  getCsList(csparams.value).then((res) => {
    tableCSData.value = res.records;
    cstotal.value = res.total;
  });
}
// 参数新增
function addCsModel() {
  iscsEdit.value = false;
  dialogcsFormVisible.value = true;
  csform.value = {
    csmc: "",
    csz: "",
    cslx: ""
  };
  csform.value.mxid = csparams.value.mxid;
}
function saveCs() {
  elcsform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    addCs(csform.value).then((res) => {
      ElMessage.success("新增成功");
      csparams.value.pageCurrent = 1;
      searchCs();
      dialogcsFormVisible.value = false;
    });
  });
}
// 参数删除
function deleteCs(row) {
  delCs(row.id).then((res) => {
    csparams.value.pageCurrent = 1;
    searchCs();
  });
}
// 参数修改
function updateCs(row) {
  iscsEdit.value = true;
  dialogcsFormVisible.value = true;
  csform.value = row;
}
function updateCsModel() {
  elcsform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    putCs(csform.value).then((res) => {
      ElMessage.success("修改成功");
      csparams.value.pageCurrent = 1;
      searchCs();
      dialogcsFormVisible.value = false;
    });
  });
}

// 参数分页相关
/**
 * size 改变触发
 */
const handleSizeChangecs = (currentSize) => {
  csform.value.pageSize = currentSize;
  searchCs();
};

/**
 * 页码改变触发
 */
const handleCurrentChangecs = (currentPage) => {
  csform.value.pageCurrent = currentPage;
  searchCs();
};

// 启动
function startModel(row) {
  getCsDTQZ(row.id).then((res) => {
    ElMessage.success("启动成功");
    handleFilter();
  });
}
// 停止
function stopModel(row) {
  getCsDTQZ(row.id).then((res) => {
    ElMessage.success("停止成功");
    handleFilter();
  });
}

const isEdit = ref(true);
const dialogForm = ref({});
const reset = () => {
  listQuery.value = {
    pageCurrent: 1,
    pageSize: 10,
    mxmc: ""
  };
  getListData();
};
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
// 获取数据的方法
const getListData = async () => {
  const res = await getYJModelList(listQuery.value);
  tableData.value = res?.records;
  total.value = Number(res.total);
};

const handleFilter = () => {
  listQuery.value.pageCurrent = 1;
  getListData();
};
getListData();

// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageCurrent = currentPage;
  getListData();
};

/**修改字典 */
const updateJob = (row) => {
  isEdit.value = true;
  dialogForm.value = { ...row };
  dialogForm.value.ssbmid = dialogForm.value.ssbmid * 1;
  dialogFormVisible.value = true;
};

const addJob = (row) => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
};
const onSave = () => {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    dialogForm.value.ssbmdm = dialogForm.value.ssbmid;
    putYJmodel({
      ...dialogForm.value
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("修改成功");
        buttonLoading.value = false;
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const onAdd = () => {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    dialogForm.value.ssbmdm = dialogForm.value.ssbmid;
    addYJmodel({
      ...dialogForm.value
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("新增成功");
        buttonLoading.value = false;
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const delRole = (row) => {
  delYJModel(row.id).then((res) => {
    ElMessage.success("删除成功");
    handleFilter();
  });
};

const closeDialog = () => {
  dialogForm.value = {};
  dialogFormVisible.value = false;
};
// 高度计算
const tabHeightFn = () => {
 tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 240;
};
onMounted(() => {
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";
.user-manage-container {
  .table-header-wrap {
    margin-bottom: 22px;
  }

  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
  }
}
.cslb_text {
  // font-size: 20px;
  color: rgb(7, 142, 231);
  padding: 10px;
}
.canshu_box {
  width: 94%;
  display: flex;
  justify-content: space-between;
}
.csmxadd {
  display: flex;
  justify-content: flex-end;
  margin: 10px;
}
.mxcs_table {
  margin: 10px;
}
</style>
