<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          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="600" 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"> </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"> </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"> </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 #paymentDays>
          <el-row :gutter="10" style="width: 100%">
            <el-col :span="8">
              <el-form-item prop="accountPeriod">
                <el-input-number v-model="formData.data.accountPeriod" placeholder="请输入账期 (天)" style="width: 100%" :precision="0" :controls="false" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item prop="accountPeriodRemark">
                <el-input v-model="formData.data.accountPeriodRemark" placeholder="请输入账期说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template #fileSlot>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              multiple
              :before-upload="uploadFile"
              :on-preview="onPreviewFile">
              <el-button>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" 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 { computed, ref } from "vue";

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");
const fileList = ref([]);
const uploadData = ref({});
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: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "供应商类型",
    prop: "type",
    data: [],
  },
]);
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: "remark",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      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: "sales",
  },
});
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: "paymentDays",
      label: "账期信息",
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "上传附件",
    },
    {
      type: "input",
      label: "备注",
      prop: "remark",
      itemType: "textarea",
    },
    {
      label: "银行信息",
    },
    {
      type: "input",
      prop: "openingName",
      label: "账户名称",
      itemType: "text",
    },
    {
      type: "input",
      prop: "openingBank",
      label: "开户银行",
      itemType: "text",
    },
    {
      type: "input",
      prop: "accountOpening",
      label: "银行账号",
      itemType: "text",
    },
    {
      type: "input",
      prop: "interbankNumber",
      label: "联行号",
      itemType: "text",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/supplierInfo/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";
  fileList.value = [];
  formData.data = {
    type: "sales",
    countryId: "China",
  };
  getCityData(formData.data.countryId, "20");
};
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitForm = () => {
  byform.value.handleSubmit(() => {
    if (fileList.value && fileList.value.length > 0) {
      formData.data.fileList = fileList.value.map((item) => {
        return {
          id: item.raw.id,
          fileName: item.raw.fileName,
          fileUrl: item.raw.fileUrl,
        };
      });
    }
    submitLoading.value = true;
    proxy.post("/supplierInfo/" + modalType.value, formData.data).then(
      () => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        submitLoading.value = false;
      }
    );
  });
};
const getDtl = (row) => {
  fileList.value = [];
  modalType.value = "edit";
  proxy.post("/supplierInfo/detail", { id: row.id }).then((res) => {
    proxy.post("/fileInfo/getList", { businessIdList: [row.id] }).then((fileObj) => {
      if (fileObj[row.id] && fileObj[row.id].length > 0) {
        fileList.value = fileObj[row.id].map((item) => {
          return {
            raw: item,
            name: item.fileName,
            url: item.fileUrl,
          };
        });
      }
      getCityData(res.countryId, "20");
      getCityData(res.provinceId, "30");
      res.type = res.type + "";
      formData.data = res;
      dialogVisible.value = true;
    });
  });
};
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;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
