<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="materialList">
                <el-select
                  v-model="materialValue"
                  multiple
                  @remove-tag="setFormMaterial"
                  ref="selectBom"
                  placeholder="请选择物料"
                  @click="startCreat"
                >
                  <el-option
                    v-for="item in formVlaue.materialList"
                    :key="item"
                    :label="item.materialName"
                    :value="item.materialCode"
                  />
                </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-select
                      v-model="addForm.paramName"
                      allow-create
                      filterable
                      default-first-option
                      :reserve-keyword="false"
                    >
                      <el-option
                        v-for="item in dicts.form_params"
                        :key="item.dictLabel"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                  </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-select v-model="addForm.source">
                      <el-option label="手动" value="手动" selected />
                      <el-option label="自动" value="自动" />
                    </el-select>
                  </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.checkStr ? JSON.parse(row.checkStr).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" style="display: flex; justify-content: center" 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>
      <CommonTable
        ref="ctableRef"
        :key="ctableRefKey"
        tableTitle="物料添加"
        :multipleRow="multipleRow"
        tableType="MARTERIAL"
        @selected-sure="onSelectedFinish"
      />
    </div>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {
  addExcel,
  delExcel,
  updateExcel,
  getSettingsData,
  addSettingsData,
  deleteSettingsData,
} from "@/api/excel";
import ExcelView from "@/components/ExcelView/index.vue";
import { useDictionaryStore } from "@/store";
const { dicts } = useDictionaryStore();
const selectKey = ref(false);
// const tableData = ref([]);
const showPosition = () => {
  if (!excelStatus) return;
  addForm.value.position = excelViewRef.value.getRangeAxis()[0];
};
const multipleRow = ref(true);
const ctableRef = ref(null);
const ctableRefKey = ref(false);
const selectBom = ref({});
const startCreat = () => {
  selectBom.value.blur();
  ctableRef.value?.mergeOption({
    selection: true,
    reserveSelection: true,
  });
  ctableRef.value.startSelect();
};
const onSelectedFinish = (selectedValueList) => {
  formVlaue.value.materialList = [];
  selectedValueList.forEach((item, index) => {
    formVlaue.value.materialList.push({
      materialCode: item.materialCode,
      materialName: item.materialName,
      spec: item.spec,
    });
  });
  ctableRefKey.value = !ctableRefKey.value;
  selectKey.value = !selectKey.value;
};
const materialValue = ref([]);
const setMaterialValue = () => {
  let array = [];
  for (let i = 0; i < formVlaue.value.materialList.length; i++) {
    array.push(formVlaue.value.materialList[i].materialCode);
  }
  materialValue.value = array;
  return array;
};
const setFormMaterial = () => {
  formVlaue.value.materialList = formVlaue.value.materialList.filter((item) => {
    const res = materialValue.value.includes(item.materialCode);
    return res;
  });
};
//初始化页面数据
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.value.materialList = [];
  formVlaue.value.formName = null;
  formVlaue.value.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: "materialCode",
      addDisplay: false,
    },
    {
      label: "物料名称",
      slot: true,
      search: true,
      headerAlign: "center",
      align: "center",
      prop: "materialName",
      addDisplay: false,
    },
    {
      label: "规格",
      slot: true,
      headerAlign: "center",
      align: "center",
      prop: "spec",
      addDisplay: false,
    },
    {
      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) => {
    options.value.edit = false;
    selectId.value = row.id;
    exceldata.value = JSON.parse(row.excelData);
    excelStatus.value = true;
    getSettingData();
  };
  //编辑
  const editTep = (row) => {
    options.value.inName = row.formName;
    exceldata.value = JSON.parse(row.excelData);
    formVlaue.value.formName = row.formName;
    formVlaue.value.state = row.state;
    selectId.value = row.id;
    operaEditStatus.value = true;
    excelStatus.value = true;
    getSettingData();
  };
  //删除
  const deleteTep = async (row) => {
    const { data, code } = await delExcel({
      id: row.id,
    });
    if (code == "200") {
      ElMessage.success("删除成功！");
      dataEditList();
    }
  };

  //获取组件内实时数据赋值到外层
  const confirm = (data) => {
    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 = ref({
    formName: null,
    materialList: [],
    state: null,
  });
  //表单是否为编辑状态变量
  const operaEditStatus = ref(false);
  //选中的行id
  const selectId = ref(null);
  //表单ref实例
  const formRef = ref(null);
  //表单校验规则
  const rules = reactive({
    formName: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    materialList: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    state: [
      {
        required: true,
        trigger: "blur",
      },
    ],
  });
  //新增模版
  const submitForm = async (formEl) => {
    //@ts-ignore;
    excelViewRef.value.confirm();
    if (exceldata.value == null) return ElMessage.error("请提供表格数据！");
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        const { data, code } = await addExcel({
          ...formVlaue.value,
          excelData: exceldata.value,
        });
        if (code == "200") {
          ElMessage.success("添加成功！");
          resetData();
          dataEditList();
        }
      }
    });
  };
  //更新行内信息
  const updateExForm = async (formEl) => {
    //@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, fields) => {
      if (valid) {
        const { data, code } = await updateExcel({
          ...formVlaue.value,
          excelData: exceldata.value,
          id: selectId.value,
          settings: settings.value,
        });
        if (code == "200") {
          ElMessage.success("修改成功！");
          resetData();
          dataEditList();
        }
      }
    });
  };
  //表达数据重置
  const resetForm = (formEl) => {
    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) => {
      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,
      source: addForm.value.source,
    });
    const { data, code } = await addSettingsData({
      excelFormId: selectId.value,
      ...addForm.value,
    });
    if (code == "200") {
      ElMessage.success("添加成功");
      resetAddForm();
      getSettingData();
    }
  };
  const deleteSettings = async (id) => {
    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, fields) => {
      if (valid) {
        addSettings();
      }
    });
  };
  const addRules = reactive({
    paramName: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    position: [
      {
        required: true,
        trigger: "blur",
      },
    ],
    up: [
      {
        required: false,
        trigger: "blur",
      },
    ],
    down: [
      {
        required: false,
        trigger: "blur",
      },
    ],
    standard: [
      {
        required: false,
        trigger: "blur",
      },
    ],
    source: [
      {
        required: false,
        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();
watch(
  () => formVlaue.value.materialList,
  (value) => {
    setMaterialValue();
  },
  {
    immediate: true,
  }
);

onMounted?.(() => {
  dataEditList();
});
</script>
<style lang="scss" scoped>
.table {
  width: 430px;
  padding-top: 20px;
}
.btns {
  width: 100%;
  justify-content: center;
  height: 40px;
  display: flex;
  align-items: center;
  .el-button {
    height: 30px;
  }
}
.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: 10px !important;
}
:deep(.el-input__inner) {
  height: 24px !important;
}
</style>
