<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[]"
        @get-list="getList"
      >
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="'调整BOM'"
      v-model="dialogVisible"
      width="800"
      v-loading="submitLoading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #slot>
          <div style="width: 100%">
            <el-button type="primary" plain @click="openMaterial = true"
              >添加物料/半成品</el-button
            >
            <el-button type="primary" plain> Excel导入</el-button>
            <el-form
              ref="tableForm"
              :model="formData.data"
              :rules="rules"
              label-width="0px"
              style="margin-top: 15px"
            >
              <el-table :data="formData.data.workOrderBomList">
                <el-table-column prop="productCode" label="物料编码" />
                <el-table-column prop="productName" label="物料名称" />
                <el-table-column
                  prop="productUnit"
                  label="单位"
                  :formatter="
                    (row) => dictValueLabel(row.productUnit, materialUnit)
                  "
                />
                <el-table-column prop="quantity" label="数量" width="150">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'workOrderBomList.' + $index + '.quantity'"
                      :rules="rules.quantity"
                      :inline-message="true"
                    >
                      <el-input-number
                        v-model="row.quantity"
                        :precision="2"
                        :controls="false"
                        :min="1"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="zip" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </template>
      </byForm>
      <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="调整工艺"
      v-model="dialogVisibleOne"
      width="800"
      v-loading="loadingOne"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfigOne"
        :formOption="formOption"
        v-model="formData.dataOne"
        :rules="rulesOne"
        ref="byformOne"
      >
        <template #slot>
          <div style="width: 100%" class="tableDrop">
            <el-button type="primary" plain @click="clickAdd"
              >添加工序</el-button
            >
            <el-table
              :data="formData.dataOne.workOrderProductionProcessesList"
              style="width: 100%; margin-top: 16px"
              row-key="id"
            >
              <el-table-column label="工序名称" width="150">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item
                      :prop="
                        'workOrderProductionProcessesList.' + $index + '.name'
                      "
                      :rules="rulesOne.name"
                      :inline-message="true"
                    >
                      <el-input v-model="row.name" placeholder="请输入" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="工艺说明" width="300">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item
                      :prop="
                        'workOrderProductionProcessesList.' +
                        $index +
                        '.remarks'
                      "
                      :rules="rulesOne.remarks"
                      :inline-message="true"
                    >
                      <el-input
                        v-model="row.remarks"
                        type="textarea"
                        placeholder="请输入"
                      />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="图纸">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item
                      :prop="
                        'workOrderProductionProcessesList.' + $index + '.name'
                      "
                      :rules="rulesOne.name"
                      :inline-message="true"
                    >
                      <el-upload
                        v-model:fileList="row.fileList"
                        :show-file-list="false"
                        class="upload-demo"
                        action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                        :data="uploadData"
                        :before-upload="
                          (file) => handleBeforeUpload(file, $index)
                        "
                        accept=".pdf"
                      >
                        <el-icon
                          :size="17"
                          style="margin-top: 12px; cursor: pointer"
                        >
                          <Edit />
                        </el-icon>
                      </el-upload>
                      <div>
                        <div>
                          <el-tag
                            style="margin-left: 10px"
                            class="ml-2"
                            type="info"
                            v-for="(item, index) in row.fileListCopy"
                            :key="index"
                            >{{ item.fileName }}</el-tag
                          >
                        </div>
                      </div>
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                align="center"
                label="操作"
                width="60"
                fixed="right"
              >
                <template #default="{ $index }">
                  <el-button type="primary" link @click="clickDelete($index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisibleOne = false" size="large"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitFormOne('byform')"
          size="large"
          :loading="loadingOne"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="openMaterial"
      title="选择产品"
      width="70%"
      append-to-body
    >
      <SelectMaterial @handleSelect="handleSelect"></SelectMaterial>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openMaterial = false">取消</el-button>
        </span>
      </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 { computed, defineComponent, nextTick, ref } from "vue";
import useUserStore from "@/store/modules/user";
import SelectMaterial from "@/components/product/SelectMaterial";
import Sortable from "sortablejs";

const uploadData = ref({});
let fileList = ref([]);
let fileListCopy = ref([]);
const loading = ref(false);
const submitLoading = ref(false);
const loadingOne = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let dialogVisibleOne = ref(false);
let openMaterial = ref(false);
let roomDialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
});
let rulesOne = ref({
  name: [{ required: true, message: "请输入工序名称", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入工艺说明", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const materialUnit = ref([]);
const workOrderSource = ref([]);
const selectConfig = computed(() => [
  {
    label: "工单来源",
    prop: "source",
    data: workOrderSource.value,
  },
]);

const config = computed(() => {
  return [
    {
      attrs: {
        label: "工单来源",
        prop: "source",
      },
      render(source) {
        return proxy.dictValueLabel(source, workOrderSource.value);
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "是否定制",
        prop: "isCustomized",
      },
      render(isCustomized) {
        return isCustomized == 1 ? "是" : "否";
      },
    },
    {
      attrs: {
        label: "工单数量",
        prop: "quantity",
      },
    },
    {
      attrs: {
        label: "已计划数量",
        prop: "arrangedQuantity",
      },
    },
    {
      attrs: {
        label: "完成率",
        prop: "completionRate",
      },
      render(completionRate) {
        if (completionRate !== undefined && completionRate !== "") {
          return completionRate + "%";
        }
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.isCustomized == 1
            ? {
                attrs: {
                  label: "调整BOM",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  getDtl(row);
                },
              }
            : {},
          row.isCustomized == 1
            ? {
                attrs: {
                  label: "调整工艺",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  getDtlOne(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
  dataOne: {},
  treeData: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const byformOne = ref(null);

const treeData = ref([]);
const formConfig = reactive([
  {
    type: "slot",
    slotName: "slot",
  },
]);
const formConfigOne = reactive([
  {
    type: "slot",
    slotName: "slot",
    label: "",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/workOrder/pageByJxst", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {};
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    submitLoading.value = true;
    proxy.post("/workOrderBom/edit", formData.data).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => (submitLoading.value = false)
    );
  });
};

const submitFormOne = () => {
  byformOne.value.handleSubmit((valid) => {
    for (
      let i = 0;
      i < formData.dataOne.workOrderProductionProcessesList.length;
      i++
    ) {
      const e = formData.dataOne.workOrderProductionProcessesList[i];
      if (!e.fileListCopy.length > 0) {
        return ElMessage({
          message: "请上传图纸",
          type: "info",
        });
      }
    }
    for (
      let i = 0;
      i < formData.dataOne.workOrderProductionProcessesList.length;
      i++
    ) {
      const e = formData.dataOne.workOrderProductionProcessesList[i];
      e.fileList = e.fileListCopy;
    }
    loadingOne.value = true;
    proxy.post("/workOrderProductionProcesses/edit", formData.dataOne).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisibleOne.value = false;
        loadingOne.value = false;
        getList();
      },
      (err) => (loadingOne.value = false)
    );
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/workOrderBom/list", { workOrderId: row.id }).then((res) => {
    formData.data = {
      workOrderBomList: res,
      workOrderId: row.id,
    };
    dialogVisible.value = true;
  });
};

const handleRemove = (index) => {
  formData.data.workOrderBomList.splice(index, 1);
};
// 对el-table进行拖拽排序
const initSort = () => {
  const tbody = document.querySelector(
    ".tableDrop .el-table__body-wrapper tbody"
  );
  Sortable.create(tbody, {
    onEnd({ newIndex, oldIndex }) {
      if (newIndex == oldIndex) return;
      formData.dataOne.workOrderProductionProcessesList.splice(
        newIndex,
        0,
        formData.dataOne.workOrderProductionProcessesList.splice(oldIndex, 1)[0]
      );
      var newArray = formData.dataOne.workOrderProductionProcessesList.slice(0);
      formData.dataOne.workOrderProductionProcessesList = [];
      nextTick(() => {
        formData.dataOne.workOrderProductionProcessesList = newArray;
      });
    },
  });
};
const getDtlOne = (row) => {
  modalType.value = "edit";
  proxy
    .post("/workOrderProductionProcesses/list", { workOrderId: row.id })
    .then((res) => {
      dialogVisibleOne.value = true;
      res = res.map((x) => ({
        ...x,
        fileList: [
          {
            fileName: x.fileName,
            id: x.oldId,
          },
        ],
        fileListCopy: [
          {
            fileName: x.fileName,
            id: x.oldId,
          },
        ],
      }));
      formData.dataOne = {
        workOrderId: row.id,
        workOrderProductionProcessesList: res,
      };
      nextTick(() => {
        initSort();
      });
    });
};

const getDict = () => {
  proxy.getDictOne(["material_unit", "work_order_source"]).then((res) => {
    materialUnit.value = res["material_unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    workOrderSource.value = res["work_order_source"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getList();
getDict();

const handleSelect = (row) => {
  const flag = formData.data.workOrderBomList.some(
    (x) => x.productId === row.id
  );
  if (flag)
    return ElMessage({
      message: "该物料已选择",
      type: "info",
    });
  formData.data.workOrderBomList.push({
    productId: row.id,
    productCode: row.code,
    productName: row.name,
    productUnit: row.unit,
    quantity: null,
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};

const clickAdd = () => {
  formData.dataOne.workOrderProductionProcessesList.push({
    fileList: [],
    fileListCopy: [],
    name: "",
    remarks: "",
  });
};
const clickDelete = (index) => {
  formData.dataOne.workOrderProductionProcessesList.splice(index, 1);
};

const handleBeforeUpload = async (file, index) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  formData.dataOne.workOrderProductionProcessesList[index].fileListCopy = [
    {
      id: res.id,
      fileName: res.fileName,
      path: res.fileUrl,
      url: res.fileUrl,
      uid: file.uid,
    },
  ];
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>