<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="[
          {
            text: '添加工序',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
        <template #fileSlot="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickFile(item)"
          >
            {{ item.fileName }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '添加工序' : '编辑工序'"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #slot>
          <div>
            <el-upload
              v-model:fileList="fileList"
              class="upload-demo"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :limit="3"
              :data="uploadData"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="handleBeforeUpload"
              accept=".pdf"
            >
              <el-button type="primary">点击上传</el-button>
              <template #file>
                <div>
                  <div style="margin-top: 15px">
                    <el-tag
                      class="ml-2"
                      type="info"
                      v-for="(item, index) in fileList"
                      :key="index"
                      closable
                      @close="handleClose(index)"
                      >{{ item.fileName }}</el-tag
                    >
                  </div>
                </div>
              </template>
            </el-upload>
          </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>
  </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 FileUpload from "@/components/FileUpload/index";
import { computed, defineComponent, ref } from "vue";
import { getToken } from "@/utils/auth";

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadData = ref({});
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let fileList = ref([]);
let rules = ref({
  name: [{ required: true, message: "请输入工序名称", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  // {
  //   label: "车间类型",
  //   prop: "type",
  //   data: [
  //     {
  //       label: "普通车间",
  //       value: "1",
  //     },
  //     {
  //       label: "半自动化车间",
  //       value: "2",
  //     },
  //     {
  //       label: "自动化车间",
  //       value: "3",
  //     },
  //   ],
  // },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "工序名称",
        prop: "name",
      },
    },
    {
      attrs: {
        label: "工序说明",
        prop: "remarks",
      },
    },
    {
      attrs: {
        label: "工序文件",
        prop: "fileName",
        slot: "fileSlot",
      },
      // render(fileName) {
      //   return <div>fileName</div>;
      // },
    },

    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            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("/productionProcesses/delete", {
                    id: row.id,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "name",
      label: "工序名称",
      required: true,
    },
    {
      type: "input",
      prop: "remarks",
      label: "工序说明",
      itemType: "textarea",
    },
    {
      type: "slot",
      slotName: "slot",
      label: "上传附件",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/productionProcesses/page", sourceList.value.pagination)
    .then((message) => {
      console.log(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 = () => {
  if (fileList.value.length > 0) {
    byform.value.handleSubmit((valid) => {
      formData.data.fileList = fileList.value;
      submitLoading.value = true;
      proxy.post("/productionProcesses/" + modalType.value, formData.data).then(
        (res) => {
          ElMessage({
            message: modalType.value == "add" ? "添加成功" : "编辑成功",
            type: "success",
          });
          fileList.value = [];
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => {
          console.log(err, "aswwwww");
          submitLoading.value = false;
        }
      );
    });
  } else {
    return ElMessage({
      message: "请上传附件！",
      type: "info",
    });
  }
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/productionProcesses/detail", { id: row.id }).then((res) => {
    fileList.value = [
      {
        id: "",
        fileName: res.fileName,
        path: "",
      },
    ];
    formData.data = res;
    dialogVisible.value = true;
  });
};
const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  fileList.value = [
    {
      id: res.id,
      fileName: res.fileName,
      path: res.fileUrl,
    },
  ];
};
const handleClickFile = (row) => {
  ElMessage({
    message: "数据请求中，请稍后！",
    type: "success",
  });
  let id = row.id;
  proxy.post("/fileInfo/getList", { businessIdList: [id] }).then((res) => {
    const file = res[id][0];
    window.open(file.fileUrl, "_blank");
  });
};

const handlePreview = (file) => {
  console.log(file);
};
const handleSuccess = (file) => {
  console.log(file);
};
const handleRemove = (file) => {
  fileList.value = [];
};
const handleClose = (index) => {
  fileList.value.splice(index, 1);
};
getList();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>