<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(),
          },
        ]"
        @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 #address>
          <el-row :gutter="10" style="width: 100%">
            <el-col :span="8">
              <el-select v-model="formData.data.aa" placeholder="国家">
                <el-option v-for="item in 3" label="ceshi" value="1">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="formData.data.aa" placeholder="省/洲">
                <el-option v-for="item in 3" label="ceshi" value="1">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="formData.data.aa" placeholder="城市">
                <el-option v-for="item in 3" label="ceshi" value="1">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="24">
              <el-input v-model="formData.data.bb" type="textarea"> </el-input>
            </el-col>
          </el-row>
        </template>

        <template #contact>
          <el-row :gutter="10" style="width: 100%">
            <el-col :span="8">
              <el-input v-model="formData.data.aa" placeholder="联系人">
              </el-input>
            </el-col>
            <el-col :span="16">
              <el-input v-model="formData.data.aa" placeholder="联系电话">
              </el-input>
            </el-col>
          </el-row>
        </template>

        <template #fileSlot>
          <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,
    status: "",
  },
});
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: "productType",
    data: [
      {
        label: "产品",
        value: "1",
      },
      {
        label: "物料",
        value: "2",
      },
    ],
  },
  {
    label: "状态",
    prop: "status",
    data: [],
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "申购单号",
        prop: "subscribeCode",
      },
    },
    {
      attrs: {
        label: "货品类型",
        prop: "productDefinition",
      },
      render(definition) {
        return definition == 1 ? "产品" : definition == 2 ? "物料" : "";
      },
    },
    {
      attrs: {
        label: "所属分类",
        prop: "productCategory",
      },
    },
    {
      attrs: {
        label: "货品编码",
        prop: "productCode",
      },
    },
    {
      attrs: {
        label: "货品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
      },
    },

    {
      attrs: {
        label: "申购数量",
        prop: "count",
      },
    },
    {
      attrs: {
        label: "收货仓库",
        prop: "receiptWarehouseName",
      },
    },
    {
      attrs: {
        label: "要求到货时间",
        prop: "planArrivalTime",
      },
    },
    {
      attrs: {
        label: "申购时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "审批状态",
        prop: "count11",
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "status",
      },
      render(status) {
        return statusData.value.find((x) => x.value == status).label;
      },
    },
    // {
    //   attrs: {
    //     label: "申购原因",
    //     prop: "subscribeContent",
    //   },
    // },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          // {
          //   attrs: {
          //     label: "修改",
          //     type: "primary",
          //     text: true,
          //   },
          //   el: "button",
          //   click() {
          //     getDtl(row);
          //   },
          // },
          row.status == 30
            ? {
                attrs: {
                  label: "作废",
                  type: "danger",
                  text: true,
                  disabled: row.status != 30,
                },
                el: "button",
                click() {
                  // 弹窗提示是否删除
                  ElMessageBox.confirm(
                    "此操作将永久作废该数据, 是否继续?",
                    "提示",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    }
                  ).then(() => {
                    // 删除
                    proxy
                      .post("/subscribeDetail/edit", {
                        ...row,
                        status: 99,
                      })
                      .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: "radio",
      prop: "name",
      label: "供应商类型",
      required: true,
      border: true,
      data: [
        { label: "贸易商", value: "1" },
        { label: "工厂", value: "2" },
      ],
    },
    {
      type: "input",
      prop: "name",
      label: "供应商名称",
      required: true,
    },
    {
      type: "slot",
      slotName: "address",
      label: "地址",
      required: true,
    },
    {
      type: "slot",
      slotName: "contact",
      label: "联系信息",
      required: true,
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "上传附件",
    },
    {
      type: "input",
      label: "备注",
      prop: "remakes",
      itemType: "textarea",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/subscribeDetail/pageByWdly  ", sourceList.value.pagination).then(
    (message) => {
      console.log(message);
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
      }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    },
    (err) => {
      loading.value = false;
    }
  );
};
const openModal = () => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "wdly_apply_purchase",
      time:Date.now(),
    },
  });
};

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);
};
const statusData = ref([
  {
    label: "审批中",
    value: "10",
  },
  {
    label: "待采购",
    value: "15",
  },
  {
    label: "部分采购",
    value: "30",
  },
  {
    label: "已采购",
    value: "20",
  },
  {
    label: "已作废",
    value: "99",
  },
]);
selectConfig[1].data = statusData.value;
getList();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>