<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 #address="{ item }">
          <div>
            {{ item.countryName }}, {{ item.provinceName }} ,
            {{ item.cityName }}, {{ item.areaDetail }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '添加供应商' : '编辑供应商'"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
      destroy-on-close
    >
      <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-form-item prop="countryId">
                <el-select
                  v-model="formData.data.countryId"
                  placeholder="国家"
                  @change="(val) => getCityData(val, '20', true)"
                >
                  <el-option
                    v-for="item in countryData"
                    :label="item.chineseName"
                    :value="item.id"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="provinceId">
                <el-select
                  v-model="formData.data.provinceId"
                  placeholder="省/洲"
                  @change="(val) => getCityData(val, '30', true)"
                >
                  <el-option
                    v-for="item in provinceData"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="cityId">
                <el-select v-model="formData.data.cityId" placeholder="城市">
                  <el-option
                    v-for="item in cityData"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="24">
              <el-form-item prop="areaDetail">
                <el-input v-model="formData.data.areaDetail" type="textarea">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template #contact>
          <el-row :gutter="10" style="width: 100%">
            <el-col :span="8">
              <el-form-item prop="contactPerson">
                <el-input
                  v-model="formData.data.contactPerson"
                  placeholder="联系人"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item prop="contactNumber">
                <el-input
                  v-model="formData.data.contactNumber"
                  placeholder="联系电话"
                  :formatter="(val) => val.replace(/[^\d\-]/g, '')"
                  :parser="(val) => val.replace(/[^\d\-]/g, '')"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template #fileSlot>
          <div>
            <el-upload
              v-model:fileList="fileList"
              :show-file-list="false"
              class="upload-demo"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="handleBeforeUpload"
            >
              <el-button type="primary">选择</el-button>
            </el-upload>
            <div>
              <div style="margin-top: 15px">
                <el-tag
                  style="margin-right: 10px"
                  class="ml-2"
                  type="info"
                  v-for="(item, index) in fileListCopy"
                  :key="index"
                  closable
                  @close="handleClose(index)"
                  >{{ item.fileName }}</el-tag
                >
              </div>
            </div>
          </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,
    type: "",
    keyword: "",
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let fileList = ref([]);
let fileListCopy = ref([]);

const checkContactNumber = (rule, val, callback) => {
  if (val === "") {
    callback(new Error("请输入联系电话"));
  } else {
    val = "aaa";
  }
  console.log(rule, val, callback, "213");
  // @input="(val) => val.replace(/[^\d]/g, '')"
};
let rules = ref({
  name: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择供应商类型", trigger: "change" }],
  countryId: [{ required: true, message: "请选择国家", trigger: "change" }],
  provinceId: [{ required: true, message: "请选择省/洲", trigger: "change" }],
  cityId: [{ required: true, message: "请选择城市", trigger: "change" }],
  // areaDetail: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  // contactNumber: [{ validator: checkContactNumber, trigger: "blur" }],
  contactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  accountPeriod: [{ required: true, message: "请输入账期", trigger: "blur" }],
  returnPeriod: [
    { required: true, message: "请输入退换货期限", trigger: "blur" },
  ],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "供应商类型",
    prop: "type",
    data: [],
  },
  {
    label: "账期",
    prop: "accountPeriodType",
    data: [
      {
        label: "有",
        value: "1",
      },
      {
        label: "无",
        value: "0",
      },
    ],
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "供应商类型",
        prop: "type",
      },
      render(type) {
        return proxy.dictDataEcho(type, supplierType.value);
      },
    },
    {
      attrs: {
        label: "供应商编码",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "供应商名称",
        prop: "name",
      },
    },
    {
      attrs: {
        label: "所在城市",
        prop: "remarks",
        slot: "address",
      },
    },
    {
      attrs: {
        label: "联系人",
        prop: "contactPerson",
      },
    },
    {
      attrs: {
        label: "联系人电话",
        prop: "contactNumber",
      },
    },
    {
      attrs: {
        label: "账期",
        prop: "accountPeriod",
      },
    },
    {
      attrs: {
        label: "退换货期限",
        prop: "returnPeriod",
      },
    },
    {
      attrs: {
        label: "备注",
        prop: "remark",
      },
    },

    {
      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("/supplierInfo/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: "radio",
      prop: "type",
      label: "供应商类型",
      required: true,
      border: true,
      data: supplierType.value.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      })),
    },
    {
      type: "input",
      prop: "name",
      label: "供应商名称",
      required: true,
    },
    {
      type: "slot",
      slotName: "address",
      prop: "countryId",
      label: "地址",
      required: true,
    },
    {
      type: "slot",
      slotName: "contact",
      prop: "contactPerson",
      label: "联系信息",
      required: true,
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "上传附件",
    },
    {
      type: "input",
      label: "备注",
      prop: "remark",
      itemType: "textarea",
    },
    {
      type: "json",
      prop: "victoriatouristJson",
      json: [
        {
          type: "number",
          prop: "accountPeriod",
          label: "账期",
          itemWidth: 33,
          controls: false,
          precision: 2,
          min: 0,
          style: {
            width: "100%",
            "margin-right": "10px",
            "text-align": "left",
          },
        },
        {
          type: "number",
          prop: "returnPeriod",
          label: "退换货期限",
          itemWidth: 33,
          controls: false,
          precision: 2,
          min: 0,
          style: {
            width: "100%",
            "text-align": "left",
          },
        },
        {
          type: "input",
          prop: "accountName",
          label: "账户名称",
          itemWidth: 100,
        },
        {
          type: "input",
          prop: "bankOfDeposit",
          label: "开户银行",
          itemWidth: 100,
        },
        {
          type: "input",
          prop: "bankAccount",
          label: "银行账号",
          itemWidth: 100,
        },
        {
          type: "input",
          prop: "interBankNo",
          label: "联行号",
          itemWidth: 100,
        },
        // {
        //   type: "date",
        //   prop: "clearancePeriod",
        //   label: "库存清空期限",
        //   itemWidth: 33.33,
        //   format: "YYYY-MM-DD",
        // },
      ],
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/supplierInfo/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);
    });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  fileList.value = [];
  fileListCopy.value = [];
  formData.data = {
    countryId: "China",
    victoriatouristJson: {},
  };
  getCityData(formData.data.countryId, "20");
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    formData.data.fileList =
      fileListCopy.value.map((x) => ({
        id: x.id,
        fileName: x.fileName,
      })) || [];
    const obj = JSON.parse(formData.data.victoriatouristJson);
    console.log(obj, "ss");
    if (obj.accountPeriod === undefined || obj.accountPeriod === "") {
      formData.data.victoriatouristJson = obj;
      return ElMessage({
        message: "请输入账期！",
        type: "info",
      });
    }
    if (obj.returnPeriod === undefined || obj.returnPeriod === "") {
      formData.data.victoriatouristJson = obj;
      return ElMessage({
        message: "请输入退换货期限！",
        type: "info",
      });
    }
    formData.data.victoriatouristJson = JSON.stringify(obj);
    submitLoading.value = true;
    proxy.post("/supplierInfo/" + modalType.value, formData.data).then(
      (res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        fileList.value = [];
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/supplierInfo/detailByWdly", { id: row.id }).then((res) => {
    proxy
      .post("/fileInfo/getList", { businessIdList: [row.id] })
      .then((fileObj) => {
        fileList.value = fileObj[row.id] || [];
        fileListCopy.value = [...fileList.value];
        getCityData(res.countryId, "20");
        getCityData(res.provinceId, "30");
        res.type = res.type + "";
        res.victoriatouristJson = res.victoriatouristJson
          ? JSON.parse(res.victoriatouristJson)
          : {};
        formData.data = res;
        dialogVisible.value = true;
      });
  });
};

const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  fileListCopy.value.push({
    id: res.id,
    fileName: res.fileName,
    path: res.fileUrl,
    url: res.fileUrl,
    uid: file.uid,
  });
};

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 handleClose = (index) => {
  // if (fileListCopy.value.length === 1) {
  //   return ElMessage({
  //     message: "最后一个附件啦！",
  //     type: "info",
  //   });
  // }
  fileList.value.splice(index, 1);
  fileListCopy.value.splice(index, 1);
};

const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);

const getCityData = (id, type, isChange) => {
  proxy.post("/areaInfo/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (isChange) {
        formData.data.provinceId = "";
        formData.data.cityId = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (isChange) {
        formData.data.cityId = "";
      }
    } else {
      countryData.value = res;
    }
  });
};
const supplierType = ref([]);
const getDict = () => {
  proxy.getDict(["supplier_type"]).then((res) => {
    supplierType.value = res["supplier_type"];
    selectConfig[0].data = supplierType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getDict();
getCityData("0");
getList();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>