<template>
  <div class="mainContentBox">
    <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 #state="scope">
        <el-switch
          active-value="1"
          inactive-value="0"
          inline-prompt
          active-text="是"
          inactive-text="否"
          v-model="scope.row.state"
          @click="changeItem($event, scope.row)"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </template>
      <template #menu-left="{ size }">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :size="size"
          @click="openDialog(0, null)"
          >新增</el-button
        >
      </template>

      <template #menu="{ size, row, index }">
        <el-button type="primary" link size="small" @click="openDialog(1, row)"
          ><i-ep-edit />编辑
        </el-button>
      </template>
      <template #menu-right="{}">
        <el-dropdown split-button
          >准备模板导入
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="downloadTemplate('/api/v1/prepareTemplate/template')"
              >
                <i-ep-download />下载模板
              </el-dropdown-item>
              <el-dropdown-item @click="importExcelData">
                <i-ep-top />导入数据
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="45%"
      @close="dialog1.visible = false"
    >
      <el-form
        ref="dataFormRef"
        :model="form"
        label-width="90px"
        :rules="rules"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="物料编码" prop="materialCode">
              <el-input
                v-model="form.materialCode"
                @click="openDialog"
                readOnly
                placeholder="请选择物料"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="materialName">
              <el-input
                v-model="form.materialName"
                disabled
                placeholder="请选择物料"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料型号" prop="materialModel">
              <el-input
                v-model="form.materialModel"
                disabled
                placeholder="请选择物料"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="物料模板" prop="template">
              <el-select
                v-model="form.template"
                multiple
                placeholder="请选择模板"
                @change="changeTemplate"
              >
                <el-option
                  v-for="item in templates"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.dictLabel"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-for="item in clickTemplates">
          <el-col :span="24">
            <el-form-item :label="item.name">
              <el-switch
                class="mb-2"
                style="
                  --el-switch-on-color: #13ce66;
                  --el-switch-off-color: #ff4949;
                "
                active-text="完成"
                inactive-text="未完成"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmit">确 定</el-button>
          <el-button @click="dialog1.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="80%"
      @close="dialog.visible = false"
    >
      <choice-item-page @material-info="materialInfo" />
    </el-dialog>
    <ExcelUpload ref="uploadRef" @finished="uploadFinished" />
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import { useCommonStoreHook } from "@/store";
import { queryDictDataByType } from "@/api/system/dict";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
const router = useRouter();

// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/prepareTemplate",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const dataFormRef = ref(ElForm);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const dialog = reactive({
  title: "物料选择",
  visible: false,
});
const dialog1 = reactive({
  title: "模板保存",
  visible: false,
});
const uploadRef = ref(null);
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show("/api/v1/prepareTemplate/importExcel");
  }
};
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  dataList();
};
const openDialog = (type, row) => {
  if (type === 0) {
    form.value.materialCode = "";
    form.value.materialName = "";
    form.value.materialModel = "";
    form.value.template = [];
    templates.value.forEach((item)=>{
      form.value.template.push(item.dictValue)
    })
    clickTemplates.value = [];
    dialog1.visible = true;
  } else if (type === 1) {
    form.value = row;
    if (!Array.isArray(row.template)) {
      form.value.template = eval("(" + row.template + ")");
    }
    //form.value.templateList = row.template.split(",")
    changeTemplate();
    dialog1.visible = true;
  } else {
    dialog.visible = true;
  }
};
const changeItem = (obj, row) => {
  form.value = { id: row.id, state: row.state };
  updateRow();
  form.value = null;
  dataList();
};
const templates = ref([]);
const clickTemplates = ref([]);
const changeTemplate = () => {
  clickTemplates.value = [];
  if (form.value.template) {
    for (let i = 0; i < form.value.template.length; i++) {
      clickTemplates.value.push({
        value: form.value.template[i],
        name: templates.value.find(
          (option) => option.dictValue === form.value.template[i]
        ).dictLabel,
      });
    }
  }
};
const onSubmit = (done, loading) => {
  dataFormRef.value.validate((isValid) => {
    if (isValid) {
      if (!form.value.id) {
        createRow(done, loading);
      } else {
        updateRow(done, loading);
      }
      dialog1.visible = false;
    }
  });
  console.log("submit!");
};
const materialInfo = (value) => {
  form.value.materialCode = value.materialCode;
  form.value.materialName = value.materialName;
  form.value.materialModel = value.spec;
  dialog.visible = false;
};
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  delBtn: true,
  selection: false,
  editBtn: false,
  viewBtn: false,
  menuBtn: true,
  menuWidth: 150,
  addBtn: false,
  dialogWidth: "45%", // 设置编辑弹窗的宽度为50%
  column: [
    {
      label: "物料编码",
      prop: "materialCode",
      search: true,
      overHidden: true,
      disabled: true,
      rules: [
        {
          required: true,
          message: "产品编码不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "产品名称",
      prop: "materialName",
      disabled: true,
      overHidden: true,
      search: true,
      rules: [
        {
          required: true,
          message: "产品名称不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "产品规格",
      prop: "materialModel",
      disabled: true,
      search: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "产品规格不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "是否启用",
      prop: "state",
      editDisplay: false,
      addDisplay: false,
      slot: true,
      width: 100,
    },
    {
      label: "创建时间",
      prop: "created",
      width: 200,
      display: false,
    },
    {
      label: "创建人",
      width: 200,
      prop: "creator",
      display: false,
    },
  ],
});
const rules = reactive({
  materialCode: [{ required: true, message: "请选择物料", trigger: "blur" }],
  template: [{ required: true, message: "请选择模板值", trigger: "blur" }],
});

onMounted(() => {
  dataList();
  queryDictDataByType("prepare_template").then((res) => {
    templates.value = res.data;
  });
});
</script>
<style scoped>
:deep(.el-progress-bar__innerText) {
  color: #737674;
  display: inline-block;
  font-size: 12px;
  margin: 0 5px;
  vertical-align: middle;
}
</style>
