<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="4" v-if="!props.expressStatus">
        <el-card :class="props.selectStatus ? 'select-card' : 'box-card'">
          <el-input v-model="filterTree" placeholder="请输入BOM分类" />
          <el-tree
            ref="treeCategory"
            :data="categoryTreeData"
            :props="{ children: 'children', label: 'name' }"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :indent="10"
            :filter-node-method="filterNodeMethod"
            @node-click="handleNodeClick" />
        </el-card>
      </el-col>
      <el-col :span="props.expressStatus ? 24 : 20">
        <el-card :class="props.selectStatus ? 'select-card' : 'box-card'">
          <byTable
            :source="sourceList.data"
            :pagination="sourceList.pagination"
            :config="config"
            :loading="loading"
            :searchConfig="searchConfig"
            :defaultExpandAll="props.selectStatus"
            highlight-current-row
            :action-list="[
              props.selectStatus
                ? ''
                : {
                    text: '添加BOM',
                    action: () => clickModal(),
                  },

              props.selectStatus
                ? ''
                : {
                    text: '操作日志',
                    action: () => viewLogs(),
                  },
            ]"
            @get-list="getList"
            @clickReset="clickReset">
            <template #typeExpand="{ item }">
              <div style="box-sizing: border-box">
                <div
                  v-for="spec in item.bomSpecList"
                  :key="spec.id"
                  style="display: flex; padding: 8px 16px; align-items: center; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1); margin-bottom: 8px">
                  <div style="width: 80px">
                    <div v-if="spec.mainImgUrl">
                      <img
                        style="width: 40px; height: 40px; object-fit: contain; vertical-align: middle; border: none; cursor: pointer"
                        :src="spec.mainImgUrl"
                        @click="openFile(spec.mainImgUrl)" />
                    </div>
                    <div
                      v-else
                      class="el-icon-picture-outline"
                      style="width: 40px; height: 40px; font-size: 36px; line-height: 40px; text-align: center; color: rgb(229 228 228)"></div>
                  </div>
                  <div style="width: 180px">
                    {{ spec.code }}
                  </div>
                  <div style="flex: 1">
                    {{ spec.name }}
                  </div>
                  <div style="width: 180px">
                    {{ `${spec.length}  *  ${spec.width}  *  ${spec.height}（cm³）` }}
                  </div>
                  <div style="width: 60px; text-align: center" v-if="props.selectStatus && !props.priceSystemId">
                    <el-button type="primary" text @click="selectBOM(spec)" :disabled="selectBtnStatus">选择</el-button>
                  </div>
                  <div style="width: 140px; padding: 0 12px" v-if="props.priceSystemId">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="spec.internalSellingPrice"
                      placeholder="对内销售价"
                      style="width: 100%"
                      :controls="false"
                      :min="0"
                      :precision="2"
                      @change="changePrice(spec)" />
                  </div>
                  <div style="width: 140px; padding: 0 12px" v-if="props.priceSystemId">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="spec.externalSellingPrice"
                      placeholder="对外销售价"
                      style="width: 100%"
                      :controls="false"
                      :min="0"
                      :precision="2"
                      @change="changePrice(spec)" />
                  </div>
                </div>
              </div>
            </template>
            <template #name="{ item }">
              <div>
                <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickName(item)">{{ item.name }}</a>
              </div>
            </template>
            <template #priceBillingStandardId="{ item }">
              <div style="width: 100%">
                <el-select v-model="item.priceBillingStandardId" placeholder="加工报价" clearable @change="changePriceBillingStandard(item)">
                  <el-option v-for="item in priceBillingStandardList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                </el-select>
              </div>
            </template>
            <template #internalSellingPrice>
              <div style="width: 100%"></div>
            </template>
            <template #externalSellingPrice>
              <div style="width: 100%"></div>
            </template>
          </byTable>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="modalTitle" v-if="openDialog" v-model="openDialog" width="90%">
      <MakeBOM :rowData="rowData" :detailStatus="detailStatus" @clickCancel="clickCancel"></MakeBOM>
    </el-dialog>

    <el-dialog title="操作日志" v-if="openLogs" v-model="openLogs" width="50%">
      <byTable
        :source="logsList.data"
        :pagination="logsList.pagination"
        :config="configLogs"
        :loading="loadingLogs"
        highlight-current-row
        @get-list="getLogsList">
      </byTable>
      <template #footer>
        <el-button @click="openLogs = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import MakeBOM from "@/components/makeBOM/index";

const { proxy } = getCurrentInstance();
const props = defineProps({
  selectStatus: Boolean,
  bomClassifyIdList: Array,
  expressStatus: Boolean,
  priceSystemId: String,
});
const filterTree = ref("");
const treeCategory = ref(null);
const categoryTreeData = ref([]);
const getTreeList = () => {
  proxy.post("/bomClassify/tree", {}).then((res) => {
    if (res && res.length > 0) {
      if (props.bomClassifyIdList) {
        categoryTreeData.value = res.filter((item) => props.bomClassifyIdList.includes(item.id));
      } else {
        categoryTreeData.value = res;
      }
    }
  });
};
getTreeList();
watch(filterTree, (val) => {
  treeCategory.value.filter(val);
});
const filterNodeMethod = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};
const handleNodeClick = (val) => {
  getList({ bomClassifyId: val.id });
};
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    name: "",
    code: "",
    species: "",
    chromatophore: "",
    frontGrain: "",
    reverseGrain: "",
    colour: "",
    bomClassifyId: "",
    bomClassifyIdList: [],
    priceSystemId: "",
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "name",
      label: "品名",
    },
    {
      type: "input",
      prop: "code",
      label: "品号",
    },
    {
      type: "select",
      prop: "species",
      dictKey: "bom_species",
      label: "种类",
    },
    {
      type: "select",
      prop: "chromatophore",
      dictKey: "bom_chromatophore",
      label: "色层",
    },
    {
      type: "select",
      prop: "embossingProcess",
      dictKey: "bom_embossingProcess",
      label: "压纹工艺",
    },
    {
      type: "select",
      prop: "frontGrain",
      dictKey: "bom_frontGrain",
      label: "正面纹路",
    },
    {
      type: "select",
      prop: "reverseGrain",
      dictKey: "bom_reverseGrain",
      label: "背面纹路",
    },
    {
      type: "input",
      prop: "colour",
      label: "颜色",
    },
  ];
});
const config = computed(() => {
  return [
    {
      type: "expand",
      attrs: {
        label: " ",
        slot: "typeExpand",
        width: 50,
      },
    },
    {
      attrs: {
        label: "群组品名",
        slot: "name",
        "min-width": 240,
      },
    },
    {
      attrs: {
        label: "项目小类",
        prop: "itemSubclass",
        width: 120,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["bom_itemSubclass"]);
      },
    },
    {
      attrs: {
        label: "种类",
        prop: "species",
        width: 120,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["bom_species"]);
      },
    },
    {
      attrs: {
        label: "色层",
        prop: "chromatophore",
        width: 100,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["bom_chromatophore"]);
      },
    },
    props.priceSystemId
      ? {
          attrs: {
            label: "加工报价",
            slot: "priceBillingStandardId",
            width: 160,
          },
        }
      : {
          attrs: {
            label: "压纹工艺",
            prop: "embossingProcess",
            width: 120,
          },
          render(val) {
            return proxy.dictKeyValue(val, proxy.useUserStore().allDict["bom_embossingProcess"]);
          },
        },
    props.priceSystemId
      ? {
          attrs: {
            label: "对内销售价(含税)",
            slot: "internalSellingPrice",
            width: 140,
          },
        }
      : {
          attrs: {
            label: "正面纹路",
            prop: "frontGrain",
            width: 120,
          },
          render(val) {
            return proxy.dictKeyValue(val, proxy.useUserStore().allDict["bom_frontGrain"]);
          },
        },
    props.priceSystemId
      ? {
          attrs: {
            label: "对内销售价(含税)",
            slot: "externalSellingPrice",
            width: 140,
          },
        }
      : {
          attrs: {
            label: "背面纹路",
            prop: "reverseGrain",
            width: 120,
          },
          render(val) {
            return proxy.dictKeyValue(val, proxy.useUserStore().allDict["bom_reverseGrain"]);
          },
        },
    props.priceSystemId
      ? {
          attrs: {
            width: 16,
          },
        }
      : {
          attrs: {
            label: "操作",
            width: 120,
            align: "center",
            fixed: "right",
          },
          renderHTML(row) {
            return [
              props.selectStatus
                ? {}
                : {
                    attrs: {
                      label: "编辑",
                      type: "primary",
                      text: true,
                    },
                    el: "button",
                    click() {
                      clickUpdate(row);
                    },
                  },
              props.selectStatus
                ? {}
                : {
                    attrs: {
                      label: "删除",
                      type: "primary",
                      text: true,
                    },
                    el: "button",
                    click() {
                      clickDelete(row);
                    },
                  },
            ];
          },
        },
  ];
});
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  if (props.bomClassifyIdList) {
    sourceList.value.pagination.bomClassifyIdList = props.bomClassifyIdList;
  }
  if (props.expressStatus) {
    sourceList.value.pagination.bomClassifyId = "1682221528948760578";
  }
  loading.value = true;
  let path = "/bom/page";
  if (props.priceSystemId) {
    path = "/priceSystem/getBomPriceDetail";
    sourceList.value.pagination.priceSystemId = props.priceSystemId;
  }
  proxy.post(path, sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  treeCategory.value.setCurrentKey(null);
  getList("", true);
};
const modalTitle = ref("添加BOM");
const openDialog = ref(false);
const rowData = ref({});
const detailStatus = ref(false);
const clickModal = () => {
  modalTitle.value = "添加BOM";
  rowData.value = {};
  detailStatus.value = false;
  openDialog.value = true;
};
const clickUpdate = (row) => {
  modalTitle.value = "编辑BOM";
  rowData.value = row;
  detailStatus.value = false;
  openDialog.value = true;
};
const clickDelete = (row) => {
  ElMessageBox.confirm("你是否确认此操作", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.post("/bom/delete", { id: row.id }).then(() => {
        ElMessage({ message: "删除成功", type: "success" });
        getList();
      });
    })
    .catch(() => {});
};
const clickCancel = (status) => {
  openDialog.value = false;
  if (status) {
    getList();
  }
};
const openFile = (path) => {
  window.open(path);
};
const clickName = (row) => {
  modalTitle.value = "BOM详情";
  rowData.value = row;
  detailStatus.value = true;
  openDialog.value = true;
};
const openLogs = ref(false);
const loadingLogs = ref(false);
const logsList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
const type = ref([
  { dictKey: "1", dictValue: "新增" },
  { dictKey: "2", dictValue: "修改" },
  { dictKey: "3", dictValue: "删除" },
]);
const configLogs = computed(() => {
  return [
    {
      attrs: {
        label: "操作时间",
        prop: "createTime",
        width: 160,
        align: "center",
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "operator",
        align: "center",
      },
    },
    {
      attrs: {
        label: "BOM品号",
        prop: "code",
        align: "center",
      },
    },
    {
      attrs: {
        label: "行为",
        prop: "type",
        width: 100,
        align: "center",
      },
      render(val) {
        return proxy.dictKeyValue(val, type.value);
      },
    },
  ];
});
const viewLogs = () => {
  logsList.value.data = [];
  logsList.value.pagination.total = 0;
  openLogs.value = true;
  getLogsList({ pageNum: 1, pageSize: 10 });
};
const getLogsList = async (req) => {
  logsList.value.pagination = { ...logsList.value.pagination, ...req };
  loadingLogs.value = true;
  proxy.post("/bomOperatingLog/page", logsList.value.pagination).then((res) => {
    logsList.value.data = res.rows;
    logsList.value.pagination.total = res.total;
    setTimeout(() => {
      loadingLogs.value = false;
    }, 200);
  });
};
const emit = defineEmits(["selectBOM"]);
const selectBtnStatus = ref(false);
const selectBOM = (item) => {
  selectBtnStatus.value = true;
  emit("selectBOM", item);
  setTimeout(() => {
    selectBtnStatus.value = false;
  }, 200);
};
const priceBillingStandardList = ref([]);
const getPriceBillingStandard = () => {
  proxy.post("/priceBillingStandard/list", {}).then((res) => {
    if (res && res.length > 0) {
      priceBillingStandardList.value = res.map((item) => {
        return {
          dictKey: item.id,
          dictValue: item.name,
        };
      });
    }
  });
};
if (props.priceSystemId) {
  getPriceBillingStandard();
}
const changePriceBillingStandard = (row) => {
  let data = {
    priceSystemId: props.priceSystemId,
    bomId: row.id,
    priceBillingStandardId: row.priceBillingStandardId,
  };
  proxy.post("/priceSystemBom/saveOrEdit", data).then();
};
const changePrice = (row) => {
  let data = {
    priceSystemId: props.priceSystemId,
    bomSpecId: row.id,
    internalSellingPrice: row.internalSellingPrice,
    externalSellingPrice: row.externalSellingPrice,
  };
  proxy.post("/priceSystemBomSpec/saveOrEdit", data).then();
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
.select-card {
  height: calc(100vh - 184px);
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
