<template>
  <div style="height: calc(100vh - 114px); overflow-y: auto; overflow-x: hidden">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #bomClassifyId>
        <div style="width: 100%">
          <el-cascader
            v-model="formData.data.bomClassifyId"
            :options="classifyList"
            :props="{ checkStrictly: true, value: 'id', label: 'name', emitPath: false }"
            clearable
            style="width: 100%" />
        </div>
      </template>
      <template #specification>
        <div style="width: 100%">
          <div>
            <el-icon style="cursor: pointer; transform: translateY(4px); font-size: 24px; margin-left: 10px" @click="addSpecification"><Plus /></el-icon>
          </div>
          <el-table :data="formData.data.bomSpecList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
            <el-table-column label="图片" align="center" width="100">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.imgFile'">
                  <el-upload
                    class="avatar-uploader"
                    action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                    :data="uploadData"
                    :show-file-list="false"
                    :on-success="
                      (response, uploadFile) => {
                        return handleSuccess(uploadFile, $index);
                      }
                    "
                    :before-upload="uploadFile">
                    <el-image v-if="row.imgFile && row.imgFile.fileUrl" :src="row.imgFile.fileUrl" fit="scale-down" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="品名" min-width="220">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.name'" :rules="rules.name" :inline-message="true" style="width: 100%">
                  <el-input v-model="row.name" placeholder="请输入品名" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="品号" min-width="160">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.code'" :rules="rules.code" :inline-message="true" style="width: 100%">
                  <el-input v-model="row.code" placeholder="请输入品号" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="颜色" width="120">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.colour'" style="width: 100%">
                  <el-input v-model="row.colour" placeholder="请输入颜色" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="100">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.costPrice'" style="width: 100%">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.costPrice"
                    placeholder="成本价"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="2" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="对内销售价（含税）" width="150">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.internalSellingPrice'" style="width: 100%">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.internalSellingPrice"
                    placeholder="对内销售价"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="2" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="对外销售价（含税）" width="150">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.externalSellingPrice'" style="width: 100%">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.externalSellingPrice"
                    placeholder="对外销售价"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="2" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="安全库存" width="100">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.safetyStock'" style="width: 100%">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.safetyStock"
                    placeholder="安全库存"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="0" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单品尺寸（长宽高，cm）" align="center" width="280">
              <template #default="{ row }">
                <el-form-item style="width: 100%">
                  <el-row>
                    <el-col :span="8">
                      <el-input-number
                        onmousewheel="return false;"
                        v-model="row.length"
                        placeholder="长"
                        style="width: 100%"
                        :controls="false"
                        :min="0"
                        :precision="2" />
                    </el-col>
                    <el-col :span="8">
                      <el-input-number
                        onmousewheel="return false;"
                        v-model="row.width"
                        placeholder="宽"
                        style="width: 100%"
                        :controls="false"
                        :min="0"
                        :precision="2" />
                    </el-col>
                    <el-col :span="8">
                      <el-input-number
                        onmousewheel="return false;"
                        v-model="row.height"
                        placeholder="高"
                        style="width: 100%"
                        :controls="false"
                        :min="0"
                        :precision="2" />
                    </el-col>
                  </el-row>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="净重（g）" width="100">
              <template #default="{ row, $index }">
                <el-form-item :prop="'bomSpecList.' + $index + '.netWeight'" style="width: 100%">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.netWeight"
                    placeholder="净重"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="2" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="80">
              <template #default="{ $index }">
                <el-button type="danger" @click="clickDelete($index)" text>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #mainImgFile>
        <div style="width: 100%">
          <div style="color: #aaaaaa">图片不超过5M,支持JPEG、JPG、PNG格式;</div>
          <div style="color: #aaaaaa">建议主图大于640*640,主题鲜明、图片清晰、提升买家满意度;</div>
          <el-upload
            class="avatar-uploader-main"
            action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
            :data="uploadMainData"
            :show-file-list="false"
            :on-success="handleMainSuccess"
            :before-upload="uploadMainFile">
            <el-image
              v-if="formData.data.mainImgFile && formData.data.mainImgFile.fileUrl"
              :src="formData.data.mainImgFile.fileUrl"
              fit="scale-down"
              class="avatar" />
            <el-icon v-else class="avatar-uploader-main-icon"><Plus /></el-icon>
          </el-upload>
        </div>
      </template>
      <template #detailText>
        <div style="width: 100%">
          <div v-if="props.detailStatus">
            <div v-html="getStyle(formData.data.detailText)"></div>
          </div>
          <Editor v-else :value="formData.data.detailText" @updateValue="updateValue" ref="editor" />
        </div>
      </template>
    </byForm>
    <div style="text-align: center; margin: 10px">
      <el-button v-if="props.detailStatus" @click="clickCancel()" size="large">关 闭</el-button>
      <el-button v-if="!props.detailStatus" @click="clickCancel()" size="large">取 消</el-button>
      <el-button type="primary" @click="submitForm()" v-if="!props.detailStatus" size="large" v-preReClick>确 定</el-button>
    </div>
  </div>
</template>

<script setup>
import byForm from "/src/components/byForm/index";
import { ElMessage } from "element-plus";
import Editor from "/src/components/Editor/index.vue";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["clickCancel"]);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: "120px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {
    detailText: "",
    mainImgFile: {},
    bomSpecList: [
      {
        imgFile: {},
        name: "",
        code: "",
        colour: "",
        costPrice: undefined,
        internalSellingPrice: undefined,
        externalSellingPrice: undefined,
        safetyStock: undefined,
        length: undefined,
        width: undefined,
        height: undefined,
        netWeight: undefined,
      },
    ],
  },
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "基本信息",
      label: "",
    },
    {
      type: "slot",
      prop: "bomClassifyId",
      slotName: "bomClassifyId",
      label: "类目",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "code",
      label: "品号",
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "name",
      label: "名称",
      itemType: "text",
    },
    {
      type: "title",
      title: "材质特征",
      label: "",
    },
    {
      type: "select",
      label: "项目小类",
      prop: "itemSubclass",
      data: proxy.useUserStore().allDict["bom_itemSubclass"],
      itemWidth: 50,
    },
    {
      type: "select",
      label: "种类",
      prop: "species",
      data: proxy.useUserStore().allDict["bom_species"],
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "material",
      label: "材质",
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "modelNumber",
      label: "型号",
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "select",
      label: "正面纹路",
      prop: "frontGrain",
      data: proxy.useUserStore().allDict["bom_frontGrain"],
      itemWidth: 50,
    },
    {
      type: "select",
      label: "背面纹路",
      prop: "reverseGrain",
      data: proxy.useUserStore().allDict["bom_reverseGrain"],
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "unit",
      label: "单位",
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "logo",
      label: "LOGO",
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "select",
      label: "色层",
      prop: "chromatophore",
      data: proxy.useUserStore().allDict["bom_chromatophore"],
      itemWidth: 50,
    },
    {
      type: "select",
      label: "售价体系",
      prop: "sellingPriceSystem",
      data: proxy.useUserStore().allDict["bom_sellingPriceSystem"],
      itemWidth: 50,
    },
    {
      type: "select",
      label: "角度",
      prop: "angle",
      data: proxy.useUserStore().allDict["bom_angle"],
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "formula",
      label: "配方",
      itemType: "text",
      itemWidth: 50,
    },
    {
      type: "select",
      label: "压纹工艺",
      prop: "embossingProcess",
      data: proxy.useUserStore().allDict["bom_embossingProcess"],
      itemWidth: 50,
    },
    {
      type: "slot",
      slotName: "specification",
      label: "规格",
    },
    {
      type: "title",
      title: "图片介绍",
      label: "",
    },
    {
      type: "slot",
      slotName: "mainImgFile",
      label: "主图",
    },
    {
      type: "slot",
      slotName: "detailText",
      label: "详情描述",
    },
  ];
});
const rules = ref({
  bomClassifyId: [{ required: true, message: "请选择类目", trigger: "change" }],
  name: [{ required: true, message: "请输入品名", trigger: "blur" }],
  code: [{ required: true, message: "请输入品号", trigger: "blur" }],
});
const classifyList = ref([]);
const getBomClassify = () => {
  proxy.post("/bomClassify/tree", {}).then((res) => {
    if (res && res.length > 0) {
      classifyList.value = res.map((item) => {
        return {
          ...item,
          disabled: true,
        };
      });
    }
  });
};
getBomClassify();
const addSpecification = () => {
  if (!props.detailStatus) {
    if (formData.data.bomSpecList && formData.data.bomSpecList.length > 0) {
      formData.data.bomSpecList.push({
        imgFile: {},
        name: "",
        code: "",
        colour: "",
        costPrice: undefined,
        internalSellingPrice: undefined,
        externalSellingPrice: undefined,
        safetyStock: undefined,
        length: undefined,
        width: undefined,
        height: undefined,
        netWeight: undefined,
      });
    } else {
      formData.data.bomSpecList = [
        {
          imgFile: {},
          name: "",
          code: "",
          colour: "",
          costPrice: undefined,
          internalSellingPrice: undefined,
          externalSellingPrice: undefined,
          safetyStock: undefined,
          length: undefined,
          width: undefined,
          height: undefined,
          netWeight: undefined,
        },
      ];
    }
  }
};
const uploadData = ref({});
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const handleSuccess = (uploadFile, index) => {
  formData.data.bomSpecList[index].imgFile = {
    id: uploadFile.raw.id,
    fileName: uploadFile.raw.fileName,
    fileUrl: uploadFile.raw.fileUrl,
  };
};
const clickDelete = (index) => {
  formData.data.bomSpecList.splice(index, 1);
};
const editor = ref(null);
const updateValue = (val) => {
  formData.data.detailText = val;
};
const uploadMainData = ref({});
const uploadMainFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadMainData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const handleMainSuccess = (response, uploadFile) => {
  formData.data.mainImgFile = {
    id: uploadFile.raw.id,
    fileName: uploadFile.raw.fileName,
    fileUrl: uploadFile.raw.fileUrl,
  };
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.bomSpecList && formData.data.bomSpecList.length > 0) {
      let type = "add";
      if (formData.data.id) {
        type = "edit";
      }
      proxy.post("/bom/" + type, formData.data).then(() => {
        ElMessage({
          message: type == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        emit("clickCancel", true);
      });
    } else {
      return ElMessage("请添加规格");
    }
  });
};
const clickCancel = () => {
  emit("clickCancel", false);
};
const props = defineProps({
  rowData: Object,
  detailStatus: Boolean,
});
onMounted(() => {
  formOption.disabled = props.detailStatus;
  if (props.rowData && props.rowData.id) {
    proxy.post("/bom/detail", { id: props.rowData.id }).then((res) => {
      for (var text in res) {
        formData.data[text] = res[text];
      }
      if (!props.detailStatus) {
        editor.value.changeHtml(formData.data.detailText);
      }
      let list = [props.rowData.id];
      if (res.bomSpecList && res.bomSpecList.length > 0) {
        list = list.concat(res.bomSpecList.map((item) => item.id));
      }
      proxy.post("/fileInfo/getList", { businessIdList: list }).then((fileObj) => {
        if (fileObj) {
          if (fileObj[props.rowData.id] && fileObj[props.rowData.id].length > 0) {
            formData.data.mainImgFile = fileObj[props.rowData.id][0];
          }
          if (formData.data.bomSpecList && formData.data.bomSpecList.length > 0) {
            for (let i = 0; i < formData.data.bomSpecList.length; i++) {
              if (fileObj[formData.data.bomSpecList[i].id] && fileObj[formData.data.bomSpecList[i].id].length > 0) {
                formData.data.bomSpecList[i].imgFile = fileObj[formData.data.bomSpecList[i].id][0];
              }
            }
          }
        }
      });
    });
  }
});
const getStyle = (text) => {
  if (text) {
    return text.replace(/\n|\r\n/g, "<br>");
  } else {
    return "";
  }
};
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
  background-color: black;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
.avatar-uploader-main .avatar {
  width: 148px;
  height: 148px;
  display: block;
  background-color: black;
}
.avatar-uploader-main .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader-main .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-main-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
</style>
