<template>
  <div class="user">
    <div class="tree">
      <treeList title="物料分类" submitType="2" :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" :action-list="[
              {
                text: '添加物料',
                action: () => openModal('add'),
                disabled: false,
              },
        ]" @get-list="getList">
        <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>
        <template #name="{ item }">
          <div>
            <span class="el-click">{{ item.name }}</span>
          </div>
        </template>
        <template #size="{ item }">
          <div v-if="item['length'] && item.width && item.height">
            <span>{{ item['length'] }}cm</span>*
            <span>{{ item.width }}cm</span>*
            <span>{{ item.height }}cm</span>
          </div>
          <div v-else></div>
        </template>
        <template #price="{ item }">
          <div v-if="item.price">
            <span>{{ item.currency }} {{ moneyFormat(item.price ,2)}}</span>
          </div>
          <div v-else></div>
        </template>
        <template #costPrice="{ item }">
          <div v-if="item.costPrice">
            <span>{{ item.currency }} {{ moneyFormat(item.costPrice ,2)}}</span>
          </div>
          <div v-else></div>
        </template>
      </byTable>
    </div>
    <el-dialog :title="modalType == 'add' ? '添加物料' : '编辑物料'" v-model="dialogVisible" width="80%" destroy-on-close>
      <div class="public_height_dialog">
        <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="formDom" v-loading="submitLoading">
          <template #size>
            <div style="width: 100%">
              <el-row>
                <el-col :span="8">
                  <el-form-item prop="length" label-width="0px" class="margin-b-0 wid100">
                    <el-input-number v-model="formData.data.length" placeholder="请输入" style="width: 100%" :precision="2" :controls="false" :min="0"
                                     onmousewheel="return false;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="width" label-width="0px" class="margin-b-0 wid100">
                    <el-input-number v-model="formData.data.width" placeholder="请输入" style="width: 100%" :precision="2" :controls="false" :min="0"
                                     onmousewheel="return false;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="height" label-width="0px" class="margin-b-0 wid100">
                    <el-input-number v-model="formData.data.height" placeholder="请输入" style="width: 100%" :precision="2" :controls="false" :min="0"
                                     onmousewheel="return false;" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </template>
        </byForm>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false" size="defualt">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="defualt" :loading="submitLoading">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import treeList from "@/components/product/treeList";
const { proxy } = getCurrentInstance();
const currencyData = computed(
  () => proxy.useUserStore().allDict["account_currency"]
);
const materialUnitData = computed(
  () => proxy.useUserStore().allDict["material_unit"]
);
const colorLayerData = computed(
  () => proxy.useUserStore().allDict["color_layer"]
);
const backLinesData = computed(
  () => proxy.useUserStore().allDict["back_lines"]
);
const frontLinesData = computed(
  () => proxy.useUserStore().allDict["front_lines"]
);
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "",
    productClassifyId: "",
    keyword: "",
    definition: "2",
  },
});
const dialogVisible = ref(false);
const modalType = ref("add");
const treeData = ref([]);
const rules = ref({
  productClassifyId: [
    { required: true, message: "请选择物料分类", trigger: "change" },
  ],
  name: [{ required: true, message: "请输入物料名称", trigger: "blur" }],
  customCode: [{ required: true, message: "请输入物料编码", trigger: "blur" }],
});
const props = defineProps({
  selectStatus: Boolean,
});
const selectConfig = computed(() => []);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "图片",
        slot: "pic",
        align: "center",
        width: 80,
      },
    },
    {
      attrs: {
        label: "物料分类",
        prop: "classifyName",
        "min-width": 150,
      },
    },
    {
      attrs: {
        label: "物料编码",
        prop: "customCode",
        width: 120,
      },
    },
    {
      attrs: {
        label: " 物料名称",
        slot: "name",
        "min-width": 150,
      },
    },
    {
      attrs: {
        label: "物料材质",
        prop: "material",
        width: 120,
      },
    },
    {
      attrs: {
        label: "物料型号",
        prop: "spec",
        width: 120,
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "unit",
        width: 80,
      },
      render(val) {
        return proxy.dictKeyValue(val, materialUnitData.value);
      },
    },
    {
      attrs: {
        label: "尺寸",
        slot: "size",
        width: 150,
      },
    },
    {
      attrs: {
        label: "净重",
        prop: "netWeight",
        width: 100,
      },
      render(val) {
        if (val) {
          return val + " kg";
        }
      },
    },
    {
      attrs: {
        label: "成本价",
        slot: "costPrice",
        width: 100,
      },
    },
    {
      attrs: {
        label: "销售价",
        slot: "price",
        width: 100,
      },
    },

    {
      attrs: {
        label: "操作",
        width: "160",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          // props.selectStatus
          //   ? {}
          //   : {
          //       attrs: {
          //         label: "复制",
          //         type: "primary",
          //         text: true,
          //       },
          //       el: "button",
          //       click() {
          //         getDtlOne(row);
          //       },
          //     },
          props.selectStatus
            ? {
                attrs: {
                  label: "选择",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickSelect(row);
                },
              }
            : {
                attrs: {
                  label: "修改",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  getDtl(row);
                },
              },
          props.selectStatus
            ? {}
            : {
                attrs: {
                  label: "删除",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  proxy
                    .msgConfirm()
                    .then((res) => {
                      proxy
                        .post("/productInfo/delete", {
                          id: row.id,
                        })
                        .then((res) => {
                          proxy.msgTip("删除成功", 1);
                          getList();
                        });
                    })
                    .catch((err) => {});
                },
              },
        ];
      },
    },
  ];
});
const formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
});
const formDom = ref(null);
const treeListData = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "title1",
      title: "基本信息",
    },
    {
      type: "treeSelect",
      prop: "productClassifyId",
      label: "物料分类",
      data: treeData.value,
      itemWidth: 100,
      disabled: false,
    },
    {
      type: "input",
      prop: "name",
      label: "物料名称",
      itemWidth: 50,
      disabled: false,
    },
    {
      type: "input",
      prop: "customCode",
      label: "物料编码",
      itemWidth: 50,
      disabled: false,
    },
    {
      type: "uploadImg",
      // limit: 1,
      // listType: "picture-card",
      // accept: ".gif, .jpeg, .jpg, .png",
      imgProp: "imageUrl",
      prop: "fileList",
      label: "物料缩略图",
    },
    {
      type: "title1",
      title: "材质特征",
    },
    {
      type: "input",
      prop: "material",
      label: "材质",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "spec",
      label: "型号",
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "frontalTexture",
      label: "正面纹路",
      data: frontLinesData.value,
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "reverseTexture",
      label: "背面纹路",
      data: backLinesData.value,
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "unit",
      label: "单位",
      data: materialUnitData.value,
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "colorLayer",
      label: "色层",
      data: colorLayerData.value,
      itemWidth: 50,
    },
    // {
    //   type: "input",
    //   prop: "remark",
    //   label: "备注",
    //   itemType: "textarea",
    // },
    {
      type: "title1",
      title: "规格",
    },
    {
      type: "input",
      prop: "color",
      label: "颜色",
      itemWidth: 50,
    },
    {
      type: "number",
      prop: "stockThreshold",
      label: "安全库存",
      precision: 2,
      min: 0,
      controls: false,
      itemWidth: 50,
    },
    {
      type: "selectInput",
      prop: "costPrice",
      selectProp: "costCurrency",
      label: "成本价",
      itemWidth: 50,
      disabledSelect: true,
      data: currencyData.value,
    },
    {
      type: "selectInput",
      prop: "price",
      selectProp: "currency",
      label: "销售价",
      itemWidth: 50,
      disabledSelect: true,
      data: currencyData.value,
    },
    {
      type: "slot",
      slotName: "size",
      prop: "size",
      label: "尺寸",
      itemWidth: 50,
      disabled: false,
    },
    {
      type: "number",
      prop: "netWeight",
      label: "净重（kg）",
      precision: 2,
      min: 0,
      controls: false,
      itemWidth: 50,
    },
  ];
});

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

    const productIdList = res.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) => {
  if (e.id != undefined) {
    sourceList.value.pagination.productClassifyId = e.id;
    getList({ productClassifyId: e.id });
  }
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    definition: "2",
    fileList: [],
  };
  if (currencyData.value && currencyData.value.length > 0) {
    formData.data.currency = currencyData.value[0].dictKey;
    formData.data.costCurrency = currencyData.value[0].dictKey;
  }
};

const submitForm = () => {
  formDom.value.handleSubmit((valid) => {
    if (!formData.data.fileList.length > 0) {
      return proxy.msgTip("请上传图片", 2);
    }
    submitLoading.value = true;
    proxy.post("/productInfo/" + modalType.value, formData.data).then(
      (res) => {
        proxy.msgTip("操作成功", 1);
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

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

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/productInfo/detail", { id: row.id }).then((res) => {
    formData.data = res;
    formData.data.fileList = row.fileList.map((x) => ({
      ...x,
      url: x.fileUrl,
      name: x.fileName,
    }));
    if (formData.data.fileList.length > 0) {
      formData.data.imageUrl = formData.data.fileList[0].fileUrl;
    }
    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 + "";
//     res.definition = "2";
//     delete res.id;
//     formData.data = res;
//     dialogVisible.value = true;
//   });
// };

const handleClickFile = (file) => {
  window.open(file.fileUrl, "_blank");
};

getTreeList();
getList();

const clickSelect = (item) => {
  proxy.$emit("selectMaterial", item);
};
</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>
