<template>
  <div class="user">
    <div class="tree">
      <treeList
        title="产品分类"
        submitType="1"
        :data="treeListData"
        v-model="sourceList.pagination.productClassifyId"
        @change="treeChange"
        @changeTreeList="getTreeList"
      >
      </treeList>
    </div>
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :statConfig="statConfig"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[
          {
            text: 'Excel导入',
            action: () => openExcel(),
            disabled: false,
          },
          {
            text: '添加产品',
            action: () => openModal('add'),
            disabled: false,
          },
        ]"
        @get-list="getList"
        @moreSearch="retrievalModal = true"
      >
        <template #pic="{ item }">
          <div v-if="item.fileList.length > 0">
            <img
              :src="item.fileList[0].fileUrl"
              class="pic"
              @click="handleClickFile(item.fileList[0])"
            />
          </div>
          <div v-else></div>
        </template>
      </byTable>
    </div>
    <el-drawer v-model="retrievalModal" direction="rtl">
      <template #header>
        <h4>高级检索</h4>
      </template>
      <template #default>
        <byForm
          :formConfig="formConfig2"
          :formOption="formOption"
          v-model="sourceList.pagination"
        >
          <template #slot> 可自定义所需功能 </template>
        </byForm>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="retrievalModal = false">取消</el-button>
          <el-button type="primary" @click="clickSearch">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog
      :title="modalType == 'add' ? '添加' : '编辑'"
      v-model="dialogVisible"
      width="500"
      v-loading="loading"
      destroy-on-close
    >
      <div class="public_height_dialog">
        <byForm
          :formConfig="formConfig"
          :formOption="formOption"
          v-model="formData.data"
          :rules="rules"
          ref="byform"
        >
          <template #productPic>
            <div>
              <el-upload
                v-model:fileList="fileList"
                action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                :data="uploadData"
                list-type="picture-card"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-upload="handleBeforeUpload"
                accept=".gif, .jpeg, .jpg, .png"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>
          </template>
        </byForm>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="Excel导入"
      v-model="openExcelDialog"
      width="400"
      v-loading="loading"
    >
      <template #footer>
        <el-button @click="openExcelDialog = false" size="large"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitExcel()"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import treeList from "@/components/product/treeList";
import useUserStore from "@/store/modules/user";
import { computed, defineComponent, ref } from "vue";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "",
    productClassifyId: "",
    keyword: "",
    definition: "1",
    name: null,
    customCode: null,
    barCode: null,
    englishName: null,
    customsCode: null,
  },
});
const retrievalModal = ref(false);
let dialogVisible = ref(false);
let openExcelDialog = ref(false);

let modalType = ref("add");
let rules = ref({
  productClassifyId: [
    { required: true, message: "请选择产品分类", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择产品类型", trigger: "change" }],
  name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  unit: [{ required: true, message: "请选择单位", trigger: "change" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "产品类型",
    prop: "type",
    data: [],
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "产品类型",
        prop: "type",
      },
      render(type) {
        return proxy.dictDataEcho(type, productType.value);
      },
    },
    {
      attrs: {
        label: "产品编码",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "图片",
        prop: "unit",
        slot: "pic",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "name",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "spec",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "unit",
      },
      render(unit) {
        return proxy.dictValueLabel(unit, productUnit.value);
      },
    },
    {
      attrs: {
        label: "产品备注",
        prop: "remark",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "160",
        align: "center",
        fixed: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "复制",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtlOne(row);
            },
          },
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              // 弹窗提示是否删除
              ElMessageBox.confirm(
                "此操作将永久删除该数据, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                // 删除
                proxy
                  .post("/productInfo/delete", {
                    id: row.id,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
let statConfig = ref([]);
const uploadData = ref({});
const fileList = ref([]);
const fileListCopy = ref([]);

let formData = reactive({
  data: {},
});
const getproductInfoStatistics = () => {
  proxy.post("/productInfo/productInfoStatistics").then((res) => {
    statConfig.value = [
      {
        label: "产品类型统计",
        data: [
          {
            label: "合计",
            num: res.amount,
            type: 1,
          },
        ],
      },
    ];
    for (let i = 0; i < res.typeList.length; i++) {
      const element = res.typeList[i];
      statConfig.value[0].data.push({
        label: element.type,
        num: element.count,
        type: i + 2,
      });
    }
  });
};
getproductInfoStatistics();
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeListData = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "treeSelect",
      prop: "productClassifyId",
      label: "产品分类",
      data: [],
    },
    {
      type: "select",
      prop: "type",
      label: "产品类型",
      required: true,
      data: [],
    },
    {
      type: "input",
      prop: "name",
      label: "产品名称",
    },
    {
      type: "input",
      prop: "spec",
      label: "规格型号",
    },
    {
      type: "input",
      prop: "barCode",
      label: "条码编号",
    },
    {
      type: "select",
      prop: "unit",
      label: "单位",
      required: true,
      data: [],
      isLoad: {
        url: "/dictTenantData/page",
        labelKey: "dictValue",
        labelVal: "dictKey",
        method: "post",
        req: {
          pageNum: 1,
          pageSize: 999,
          dictCode: "unit",
          tenantId: useUserStore().user.tenantId,
        },
        resUrl: "rows",
      },
    },
    {
      type: "slot",
      slotName: "productPic",
      prop: "fileList",
      label: "产品图片",
    },
    {
      type: "input",
      prop: "remark",
      label: "备注",
      itemType: "textarea",
    },
    {
      type: "json",
      prop: "standardJson",
      json: [
        {
          type: "input",
          prop: "englishName",
          label: "英文名",
        },
        {
          type: "input",
          prop: "code",
          label: "备注",
        },
        {
          type: "input",
          prop: "netWeight",
          label: "净重",
        },
        {
          type: "input",
          prop: "customsCode",
          label: "海关编码",
        },
      ],
    },
  ];
});
const formConfig2 = computed(() => {
  return [
    {
      type: "treeSelect",
      prop: "productClassifyId",
      label: "产品分类",
      data: [],
    },
    {
      type: "select",
      prop: "type",
      label: "产品类型",
      required: true,
      data: [],
    },
    {
      type: "input",
      prop: "name",
      label: "产品名称",
    },
    {
      type: "input",
      prop: "spec",
      label: "自定义编码",
    },
    {
      type: "input",
      prop: "barCode",
      label: "条码编号",
    },
    {
      type: "input",
      prop: "englishName",
      label: "英文名",
    },
    {
      type: "input",
      prop: "customsCode",
      label: "海关编码",
    },
  ];
});
const newPassword = () => {
  formData.data.password = generatePassword();
};
const generatePassword = () => {
  var length = 12,
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    password = "";
  for (var i = 0, n = charset.length; i < length; ++i) {
    password += charset.charAt(Math.floor(Math.random() * n));
  }
  return password;
};

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/productInfo/page", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows.map((x) => ({ ...x, fileList: [] }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);

      const productIdList = message.rows.map((x) => x.id);
      // 请求文件数据并回显
      if (productIdList.length > 0) {
        proxy
          .post("/fileInfo/getList", { businessIdList: productIdList })
          .then((fileObj) => {
            for (let i = 0; i < sourceList.value.data.length; i++) {
              const e = sourceList.value.data[i];
              for (const key in fileObj) {
                if (e.id === key) {
                  e.fileList = fileObj[key];
                }
              }
            }
          });
      }
    });
};

const treeChange = (e) => {
  console.log(e);
  sourceList.value.pagination.productClassifyId = e.id;
  getList({ productClassifyId: e.id });
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    definition: "1",
    // type: "1",
    fileList: [],
    standardJson: {},
  };

  fileList.value = [];
  fileListCopy.value = [];
};

const openExcel = () => {
  openExcelDialog.value = true;
};
const submitExcel = () => {
  openExcelDialog.value = false;
};
const TreetenantId = ref("");
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
  console.log(_selection.length);
};

const tree = ref(null);
const submitForm = () => {
  console.log(byform.value);
  byform.value.handleSubmit((valid) => {
    formData.data.fileList = fileListCopy.value.map((x) => ({
      id: x.id,
      fileName: x.fileName,
    }));
    submitLoading.value = true;
    proxy.post("/productInfo/" + modalType.value, formData.data).then(
      (res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        formData.data.standardJson = JSON.parse(formData.data.standardJson);
        submitLoading.value = false;
      }
    );
  });
};

const getTreeList = () => {
  proxy
    .post("/productClassify/tree", { parentId: "", name: "", definition: "1" })
    .then((message) => {
      treeListData.value = message;
      formConfig.value[0].data = message;
      formConfig2.value[0].data = message;
      formConfig2.value[0].data.unshift({
        id: "",
        label: "全部",
        children: [],
      });
    });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/productInfo/detail", { id: row.id }).then((res) => {
    fileList.value = row.fileList.map((x) => ({ ...x, url: x.fileUrl }));
    fileListCopy.value = [...fileList.value];
    res.type = res.type + ""; //type回显
    res.definition = "1"; //产品
    res.standardJson = res.standardJson ? JSON.parse(res.standardJson) : {};
    formData.data = res;
    dialogVisible.value = true;
  });
};

const getDtlOne = (row) => {
  modalType.value = "add";
  proxy.post("/productInfo/detail", { id: row.id }).then((res) => {
    fileList.value = [];
    fileListCopy.value = [];
    res.type = res.type + ""; //type回显
    res.definition = "1"; //产品
    res.standardJson = JSON.parse(res.standardJson);
    delete res.id;
    formData.data = res;
    dialogVisible.value = true;
  });
};
getTreeList();
getList();
const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  fileListCopy.value.push({
    id: res.id,
    fileName: res.fileName,
    path: res.fileUrl,
    url: res.fileUrl,
    uid: file.uid,
  });
};

const handleSuccess = (res, file, files) => {
  // 查当前file的index值去赋值对应的copy变量的值
  // let uid = file.uid;
  // const index = fileList.value.findIndex((x) => x.uid === uid);
  // fileListCopy.value[index].uid = uid;
};

const handleRemove = (file) => {
  const index = fileListCopy.value.findIndex(
    (x) => x.uid === file.uid || x.id === file.id
  );
  fileListCopy.value.splice(index, 1);
};

const handleClickFile = (file) => {
  window.open(file.fileUrl, "_blank");
};
const productType = ref([]);
const productUnit = ref([]);
const getDict = () => {
  proxy.getDictOne(["product_type", "unit"]).then((res) => {
    productType.value = res["product_type"];
    formConfig.value[1].data = productType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    formConfig2.value[1].data = productType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    formConfig2.value[1].data.unshift({
      id: "",
      name: "全部",
    });
    selectConfig[0].data = productType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getDict();
const clickSearch = () => {
  sourceList.value.pagination.keyword = '';
  getList()
}
</script>
  
<style lang="scss" scoped>
.user {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  .tree {
    width: 300px;
  }
  .content {
    width: calc(100% - 320px);
  }
}
.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
</style>