<template>
  <div class="mainContentBox">
    <div class="body">
      <div v-if="!excelStatus">
        <avue-crud
          ref="crudRef"
          v-model:search="search"
          v-model="form"
          :data="data"
          :option="option"
          v-model:page="page"
          @row-save="createRow"
          @row-update="updateRow"
          @row-del="deleteRow"
          @search-change="searchChange"
          @search-reset="resetChange"
          @size-change="dataList"
          @current-change="dataList"
          @selection-change="selectionChange"
        >
          <template #menu-left="{}">
            <el-button
              @click="addTemplate"
              class="ml-3"
              type="primary"
              icon="el-icon-plus"
            >
              新 增
            </el-button>
          </template>
          <template #menu="{ row, index, type }">
            <el-button @click="lookTep(row)" text type="primary"
              >查看</el-button
            >
            <el-button @click="editTep(row)" text type="primary"
              >编辑</el-button
            >

            <el-popconfirm
              :visible="row.dialogVisible"
              title="您确认删除吗？"
              width="200"
              @cancel="row.dialogVisible = false"
              @confirm="deleteTep(row)"
            >
              <template #reference>
                <el-button @click="row.dialogVisible = true" text type="primary"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </avue-crud>
      </div>
      <div v-if="excelStatus" :key="excelKey" class="editView">
        <div class="exView" @mouseup="showPosition">
          <ExcelView
            ref="excelViewRef"
            :option="options"
            @confirm="confirm"
            v-model:data="exceldata"
          />
        </div>
        <div class="form" v-if="options.edit">
          <el-scrollbar>
            <el-form
              ref="formRef"
              :model="formVlaue"
              :rules="rules"
              label-width="auto"
              :show-message="false"
              status-icon
            >
              <el-form-item label="表格名称" prop="formName">
                <el-input v-model="formVlaue.formName" />
              </el-form-item>
              <el-form-item label="表格类型" prop="formType">
                <el-select
                  v-model="formVlaue.formType"
                  placeholder="请选择表格类型"
                >
                  <el-option
                    v-for="(item, index) in dicts.excel_type"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="启用状态" prop="state">
                <el-select v-model="formVlaue.state" placeholder="请选择状态">
                  <el-option
                    v-for="(item, index) in dicts.excel_states"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <div class="btns">
                  <el-button
                    v-if="!operaEditStatus"
                    type="primary"
                    @click="submitForm(formRef)"
                  >
                    创 建
                  </el-button>
                  <el-button
                    v-if="operaEditStatus"
                    type="primary"
                    @click="updateExForm(formRef)"
                  >
                    更 新
                  </el-button>
                  <el-button v-if="!operaEditStatus" @click="resetForm(formRef)"
                    >重 置</el-button
                  >
                  <el-button type="primary" @click="resetData">
                    取 消
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
            <div class="add">
              <div class="body">
                <el-form
                  ref="formRef1"
                  :model="addForm"
                  :rules="addRules"
                  label-width="auto"
                  status-icon
                  :show-message="false"
                  style="width: 410px"
                >
                  <el-form-item label="数据名称" prop="paramName">
                    <el-input v-model="addForm.paramName" />
                  </el-form-item>
                  <el-form-item label="同步坐标" prop="position">
                    <el-input :disabled="true" v-model="addForm.position" />
                  </el-form-item>
                  <el-form-item label="上限值" prop="up">
                    <el-input v-model="addForm.up" />
                  </el-form-item>
                  <el-form-item label="下限值" prop="down">
                    <el-input v-model="addForm.down" />
                  </el-form-item>
                  <el-form-item label="标准值" prop="standard">
                    <el-input v-model="addForm.standard" />
                  </el-form-item>
                  <el-form-item label="数据来源" prop="source">
                    <el-input v-model="addForm.source" />
                  </el-form-item>
                  <el-form-item>
                    <div class="btns">
                      <el-button
                        :disabled="!operaEditStatus"
                        type="primary"
                        @click="creatAddForm()"
                      >
                        新增
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <div class="table">
              <el-table
                id="table"
                border
                :data="settings"
                style="width: 430px; max-height: 240px"
              >
                <el-table-column prop="paramName" label="名称" />
                <el-table-column prop="position" label="坐标" />
                <el-table-column prop="checkStr" width="60" label="上限值">
                  <template #default="{ row }">
                    <span>{{ row.up ? row.up : "-" }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="checkStr" width="60" label="下限值">
                  <template #default="{ row }">
                    <span>{{ row.down ? row.down : "-" }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="checkStr" width="60" label="标准值">
                  <template #default="{ row }">
                    <span>{{ row.standard ? row.standard : "-" }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="checkStr" width="60" label="数据来源">
                  <template #default="{ row }">
                    <span>{{ row.source ? row.source : "-" }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60">
                  <template #default="{ row }">
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="deleteSettings(row.id)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="btns">
              <el-button
                :disabled="searchForm.pageNo == 1"
                link
                type="primary"
                @click="deletePage"
              >
                上一页
              </el-button>
              <el-button
                :disabled="
                  searchForm.totalPages == searchForm.pageNo ||
                  searchForm.totalPages == 0
                "
                link
                type="primary"
                @click="addPage"
              >
                下一页
              </el-button>
            </div>
          </el-scrollbar>
        </div>
        <div class="form" v-else>
          <el-button type="primary" @click="resetData"> 返 回 </el-button>
          <div class="table">
            <el-table
              border
              :data="settings"
              style="width: 450px; max-height: 240px"
            >
              <el-table-column prop="paramName" label="数据名称" />
              <el-table-column prop="position" label="同步坐标" />
            </el-table>
            <div class="btns">
              <el-button
                :disabled="searchForm.pageNo == 1"
                link
                type="primary"
                @click="deletePage"
              >
                上一页
              </el-button>
              <el-button
                :disabled="
                  searchForm.totalPages == searchForm.pageNo ||
                  searchForm.totalPages == 0
                "
                link
                type="primary"
                @click="addPage"
              >
                下一页
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {
  addExcel,
  delsExcel,
  delExcel,
  getInfo,
  updateExcel,
  getSettingsData,
  addSettingsData,
  deleteSettingsData,
} from "@/api/excel";
import ExcelView from "@/components/ExcelView/index.vue";
import { useDictionaryStore } from "@/store";
const { dicts } = useDictionaryStore();
// const tableData = ref([]);
const showPosition = () => {
  if (!excelStatus) return;
  addForm.value.position = excelViewRef.value.getRangeAxis()[0];
};
//初始化页面数据
const resetData = () => {
  excelViewRef.value.saveCellData();
  excelViewRef.value.reset();
  resetAddForm();
  excelKey.value = excelKey.value + 1;
  options.value = {
    opreaState: true,
    in: true,
    out: true,
    print: true,
    edit: true,
  };
  exceldata.value = null;
  selectId.value = null;
  operaEditStatus.value = false;
  resetForm(formRef.value);
  formVlaue.formType = null;
  formVlaue.formName = null;
  formVlaue.state = null;
  excelStatus.value = false;
};
// 数据字典相关

// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/excelForm",
  });
const {
  dataEditList,
  createRow,
  updateRow,
  deleteRow,
  searchChange,
  dataList,
  resetChange,
} = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件

const crudRef = ref(null); //crudRef.value 获取avue-crud对象

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  selection: false,
  viewBtn: false,
  editBtn: false,
  delBtn: false,
  addBtn: false,
  menu: true,
  column: [
    {
      label: "表格名称",
      prop: "formName",
      headerAlign: "center",
      align: "center",
      search: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "请填写图纸编号",
          trigger: "blur",
        },
      ],
    },
    {
      label: "表格类型",
      slot: true,
      search: true,
      headerAlign: "center",
      align: "center",
      prop: "formType",
      addDisplay: false,
      dicData: dicts.excel_type,
      props: { label: "dictLabel", value: "dictValue" },
    },
    {
      label: "表格状态",
      slot: true,
      search: true,
      headerAlign: "center",
      align: "center",
      prop: "state",
      addDisplay: false,
      dicData: dicts.excel_states,
      props: { label: "dictLabel", value: "dictValue" },
    },
    {
      label: "修改时间",
      slot: true,
      headerAlign: "center",
      align: "center",
      prop: "updated",
      addDisplay: false,
    },
  ],
});
// 存放操作表格相关业务代码
const useAddTemplateHook = () => {
  //excelView 组件实例
  const excelViewRef = ref(null);
  //表格配置项
  const options = ref({
    //头部操作区域
    opreaState: true,
    //导入按钮展示
    in: true,
    //导出按钮展示
    out: true,
    print: true,
    //编辑状态 false：为查看状态
    edit: true,
    //当前操作表格名称
    inName: "",
  });
  //双向绑定表格data变量
  const exceldata = ref(null);
  //控制表格组件展示界面变量（包括表格展示页面和操作页面）
  const excelStatus = ref(false);
  //新增模版
  const addTemplate = () => {
    excelStatus.value = true;
  };
  //查看
  const lookTep = (row: any) => {
    options.value.edit = false;
    selectId.value = row.id;
    exceldata.value = JSON.parse(row.excelData);
    excelStatus.value = true;
    getSettingData();
  };
  //编辑
  const editTep = (row: any) => {
    options.value.inName = row.formName;
    exceldata.value = JSON.parse(row.excelData);
    formVlaue.formType = row.formType;
    formVlaue.formName = row.formName;
    formVlaue.state = row.state;
    selectId.value = row.id;
    operaEditStatus.value = true;
    excelStatus.value = true;
    getSettingData();
  };
  //删除
  const deleteTep = async (row: any) => {
    const { data, code } = await delExcel({
      id: row.id,
    });
    if (code == "200") {
      ElMessage.success("删除成功！");
      dataEditList();
    }
  };

  //获取组件内实时数据赋值到外层
  const confirm = (data: any) => {
    exceldata.value = data;
  };
  return {
    excelStatus,
    options,
    addTemplate,
    confirm,
    exceldata,
    excelViewRef,
    lookTep,
    editTep,
    deleteTep,
  };
};
const {
  excelStatus,
  options,
  addTemplate,
  confirm,
  exceldata,
  excelViewRef,
  lookTep,
  editTep,
  deleteTep,
} = useAddTemplateHook();
const useFormHook = () => {
  //KEY告知组件刷新
  const excelKey = ref(1);
  //表单data
  const formVlaue = reactive({ formType: null, formName: null, state: null });
  //表单是否为编辑状态变量
  const operaEditStatus = ref(false);
  //选中的行id
  const selectId = ref(null);
  //表单ref实例
  const formRef = ref(null);
  //表单校验规则
  const rules = reactive({
    formName: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    formType: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    state: [
      {
        required: true,
        trigger: "blur",
      },
    ],
  });
  //新增模版
  const submitForm = async (formEl: any) => {
    //@ts-ignore;
    excelViewRef.value.confirm();
    if (exceldata.value == null) return ElMessage.error("请提供表格数据！");
    if (!formEl) return;
    await formEl.validate(async (valid: any, fields: any) => {
      if (valid) {
        const { data, code } = await addExcel({
          ...formVlaue,
          excelData: exceldata.value,
        });
        if (code == "200") {
          ElMessage.success("添加成功！");
          resetData();
          dataEditList();
          editTep(data);
        }
      }
    });
  };
  //更新行内信息
  const updateExForm = async (formEl: any) => {
    //@ts-ignore;
    excelViewRef.value.saveCellData();
    //@ts-ignore;
    excelViewRef.value.confirm();
    if (exceldata.value == null) return ElMessage.error("请提供表格数据！");
    if (!formEl) return;
    await formEl.validate(async (valid: any, fields: any) => {
      if (valid) {
        const { data, code } = await updateExcel({
          ...formVlaue,
          excelData: exceldata.value,
          id: selectId.value,
          settings: settings.value,
        });
        if (code == "200") {
          ElMessage.success("修改成功！");
          resetData();
          dataEditList();
        }
      }
    });
  };
  //表达数据重置
  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
  };
  return {
    formVlaue,
    formRef,
    rules,
    selectId,
    excelKey,
    operaEditStatus,
    submitForm,
    resetForm,
    updateExForm,
  };
};

const {
  formVlaue,
  formRef,
  rules,
  selectId,
  excelKey,
  operaEditStatus,
  submitForm,
  resetForm,
  updateExForm,
} = useFormHook();
//表格新增 分页
const useAddFormHook = () => {
  const formRef1 = ref(null);
  const settings = ref([]);
  const searchForm = ref({
    pageNo: 1,
    pageSize: 5,
    totalPages: 0,
  });
  const addForm = ref({
    paramName: "",
    position: "",
    up: "",
    down: "",
    standard: "",
    source: "",
  });
  const addPage = () => {
    searchForm.value.pageNo = searchForm.value.pageNo + 1;
    getSettingData();
  };
  const deletePage = () => {
    searchForm.value.pageNo = searchForm.value.pageNo - 1;
    getSettingData();
  };
  const getSettingData = async () => {
    const { data } = await getSettingsData({
      excelFormId: selectId.value,
      ...searchForm.value,
    });
    settings.value = data.records;
    settings.value.forEach((item: any) => {
      if (item.checkStr) {
        item.up = JSON.parse(item.checkStr).up;
        item.down = JSON.parse(item.checkStr).down;
        item.standard = JSON.parse(item.checkStr).standard;
        item.source = JSON.parse(item.checkStr).source;
      }
    });
    if (settings.value.length == 0 && searchForm.value.pageNo > 1) {
      deletePage();
    }
    searchForm.value.totalPages = data.totalPages;
  };
  const addSettings = async () => {
    addForm.value.checkStr = JSON.stringify({
      up: addForm.value.up,
      down: addForm.value.down,
      standard: addForm.value.standard,
    });
    const { data, code } = await addSettingsData({
      excelFormId: selectId.value,
      ...addForm.value,
    });
    if (code == "200") {
      ElMessage.success("添加成功");
      resetAddForm();
      getSettingData();
    }
  };
  const deleteSettings = async (id: any) => {
    const { data, code } = await deleteSettingsData({ id: id });
    if (code == "200") {
      ElMessage.success("删除成功");
      getSettingData();
    }
  };

  const resetAddForm = () => {
    addForm.value = {
      paramName: "",
      position: "",
    };
    searchForm.value = {
      pageNo: 1,
      pageSize: 5,
      totalPages: 0,
    };
    settings.value = [];
  };
  const creatAddForm = async () => {
    await formRef1.value.validate(async (valid: any, fields: any) => {
      if (valid) {
        addSettings();
      }
    });
  };
  const addRules = reactive({
    paramName: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    position: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    up: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    down: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    standard: [
      {
        required: true,
        trigger: "blur",
      },
    ],
  });
  return {
    formRef1,
    addForm,
    searchForm,
    settings,
    addRules,
    creatAddForm,
    resetAddForm,
    getSettingData,
    addSettings,
    addPage,
    deleteSettings,
    deletePage,
  };
};

const {
  formRef1,
  addForm,
  searchForm,
  settings,
  addRules,
  creatAddForm,
  deletePage,
  addPage,
  resetAddForm,
  getSettingData,
  deleteSettings,
} = useAddFormHook();

onMounted?.(() => {
  dataEditList();
});
</script>
<style lang="scss" scoped>
.table {
  width: 430px;
  padding-top: 20px;
}
.btns {
  width: 100%;
  justify-content: center;
  height: 30px;
  display: flex;
  align-items: center;
  .el-button {
    height: 20px;
  }
}
.add {
  width: 430px;
  height: 220px;
  display: flex;
  flex-direction: column;
  .body {
    display: flex;
    width: 430px;
    flex: 1;
  }
}
#table {
  height: calc(100vh - 540px) !important;
}
.editView {
  width: 100%;
  height: calc(100vh - 140px);
  display: flex;

  .exView {
    position: relative;
    width: calc(100% - 450px);
    height: 100%;
  }
  .form {
    width: 450px;
    height: 100%;
    font-size: 24px;
    padding: 20px;
    padding-right: 0px;

    .title {
      text-align: center;
      margin-bottom: 10px;
    }
    .btns {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
:deep(.el-form-item) {
  margin-bottom: 2px !important;
}
:deep(.el-input__inner) {
  height: 24px !important;
}
</style>
