<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>
            <span v-if="item.countryName"> {{ item.countryName }} ,</span
            ><span v-if="item.provinceName">{{ item.provinceName }} ,</span>
            <span v-if="item.cityName">{{ item.cityName }}</span>
          </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 #countryId>
          <div>
            <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"
              >
              </el-option>
            </el-select>
          </div>
        </template>

        <template #provinceId>
          <div>
            <selectCity
              placeholder="省/洲"
              @change="(val) => getCityData(val, '30', true)"
              addressId="provinceId"
              addressName="provinceName"
              v-model="formData.data"
              :data="provinceData"
            >
            </selectCity>
          </div>
        </template>

        <template #cityId>
          <div>
            <selectCity
              placeholder="城市"
              addressId="cityId"
              addressName="cityName"
              v-model="formData.data"
              :data="cityData"
            >
            </selectCity>
          </div>
        </template>

        <template #contactNumber>
          <div style="width: 100%">
            <el-input
              v-model="formData.data.contactNumber"
              placeholder="联系电话"
              :formatter="(val) => val.replace(/[^\d\-]/g, '')"
              :parser="(val) => val.replace(/[^\d\-]/g, '')"
            >
            </el-input>
          </div>
        </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"
              :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";
import selectCity from "@/components/selectCity/index.vue";

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",
        width: 150,
      },
    },
    {
      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: "countryId",
      prop: "countryId",
      label: "地址",
      itemWidth: 33.33,
    },
    {
      type: "slot",
      slotName: "provinceId",
      label: " ",
      itemWidth: 33.33,
    },
    {
      type: "slot",
      slotName: "cityId",
      prop: "cityId",
      label: " ",
      itemWidth: 33.33,
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "areaDetail",
    },
    {
      type: "input",
      prop: "contactPerson",
      label: "联系信息",
      placeholder: "联系人",
      required: true,
      itemWidth: 30,
    },
    {
      type: "slot",
      slotName: "contactNumber",
      prop: "contactNumber",
      label: " ",
      itemWidth: 70,
    },

    {
      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 = {
    victoriatouristJson: {},
    countryId: "44",
  };
  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);
    if (
      obj.accountPeriod === undefined ||
      obj.accountPeriod === "" ||
      obj.accountPeriod === null
    ) {
      formData.data.victoriatouristJson = obj;
      return ElMessage({
        message: "请输入账期！",
        type: "info",
      });
    }
    if (
      obj.returnPeriod === undefined ||
      obj.returnPeriod === "" ||
      obj.returnPeriod === null
    ) {
      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) => {
  fileList.value.splice(index, 1);
  fileListCopy.value.splice(index, 1);
};

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

const getCityData = (id, type, flag) => {
  proxy.post("/customizeArea/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (flag) {
        formData.data.provinceId = "";
        formData.data.provinceName = "";
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (flag) {
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } 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>