<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :selectConfig="selectConfig"
        highlight-current-row
        :action-list="[
          {
            text: '添加发票',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
      </byTable>
    </div>

    <el-dialog
      :title="modalType == 'add' ? '添加发票' : '编辑发票'"
      v-if="dialogVisible"
      v-model="dialogVisible"
      width="600"
      v-loading="loadingDialog"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="submit"
      >
        <template #money>
          <div style="width: 100%">
            <el-input-number
              v-model="formData.data.money"
              placeholder="请输入开票金额"
              :precision="2"
              :controls="false"
              :min="0"
            />
          </div>
        </template>
        <template #file>
          <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>
        <template #information>
          <el-table
            :data="formData.data.invoiceDetailsList"
            style="width: 100%; margin-top: 16px"
          >
            <el-table-column prop="code" label="采购合同" width="140" />
            <el-table-column prop="amount" label="合同金额" width="120" />
            <el-table-column
              prop="sumInvoiceMoney"
              label="已收发票金额"
              width="120"
            />
            <el-table-column label="关联金额">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'invoiceDetailsList.' + $index + '.money'"
                  :rules="rules.money"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.money"
                    placeholder="请输入关联金额"
                    style="width: 100%"
                    :precision="2"
                    :controls="false"
                    :min="0"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const invoiceType = ref([]);
const supplierList = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    invoiceType: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "发票类型",
      prop: "invoiceType",
      data: invoiceType.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "供应商",
        prop: "supplyName",
        width: 200,
      },
    },
    {
      attrs: {
        label: "发票类型",
        prop: "type",
        width: 160,
      },
      render(type) {
        let text = "";
        if (invoiceType.value && invoiceType.value.length > 0) {
          let data = invoiceType.value.filter((item) => item.value == type);
          if (data && data.length > 0) {
            text = data[0].label;
          }
        }
        return text;
      },
    },
    {
      attrs: {
        label: "发票金额",
        prop: "money",
        width: 160,
      },
    },
    {
      attrs: {
        label: "关联合同",
        prop: "purchaseCodes",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              update(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm(
                "此操作将永久删除该数据, 是否继续?",
                "提示",
                {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }
              ).then(() => {
                proxy
                  .post("/invoice/delete", {
                    id: row.id,
                  })
                  .then(() => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "invoice_type",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        invoiceType.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        supplierList.value = res.rows.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      }
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/invoice/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const fileList = ref([]);
const uploadData = ref({});
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "select",
      label: "供应商",
      prop: "supplyId",
      data: supplierList.value,
      fn: (val) => {
        changeSupply(val);
      },
      disabled: formData.data.id,
    },
    {
      type: "select",
      label: "发票类型",
      prop: "type",
      data: invoiceType.value,
    },
    {
      type: "slot",
      prop: "money",
      slotName: "money",
      label: "开票金额",
    },
    {
      type: "slot",
      prop: "file",
      slotName: "file",
      label: "上传附件",
    },
    {
      type: "slot",
      prop: "information",
      slotName: "information",
      label: "发票信息",
    },
  ];
});
const rules = ref({
  supplyId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  type: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  money: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const formData = reactive({
  data: {
    invoiceDetailsList: [],
  },
});
const openModal = (val) => {
  modalType.value = val;
  fileList.value = [];
  formData.data = {
    invoiceDetailsList: [],
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const changeSupply = (val) => {
  if (val) {
    proxy.get("/purchase/getListBySupplyId", { supplyId: val }).then((res) => {
      if (res.data && res.data.length > 0) {
        formData.data.invoiceDetailsList = res.data.map((item) => {
          return {
            purchaseId: item.id,
            code: item.code,
            amount: item.amount,
            sumInvoiceMoney: item.sumInvoiceMoney,
            money: undefined,
            remark: "",
          };
        });
      } else {
        formData.data.invoiceDetailsList = [];
      }
    });
  } else {
    formData.data.invoiceDetailsList = [];
  }
};
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 = () => {
  submit.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,
        };
      });
    }
    if (
      !(
        formData.data.invoiceDetailsList &&
        formData.data.invoiceDetailsList.length > 0
      )
    ) {
      return ElMessage("该供应商暂无关联合同");
    }
    let money = 0;
    for (let i = 0; i < formData.data.invoiceDetailsList.length; i++) {
      money = parseFloat(
        Number(money) + Number(formData.data.invoiceDetailsList[i].money)
      ).toFixed(2);
    }
    if (money != formData.data.money) {
      return ElMessage("开票金额不等于关联金额");
    }
    loadingDialog.value = true;
    proxy.post("/invoice/" + modalType.value, formData.data).then(
      () => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const update = (row) => {
  fileList.value = [];
  modalType.value = "edit";
  loadingDialog.value = true;
  proxy.post("/invoice/detail", { id: row.id }).then((res) => {
    proxy
      .post("/fileInfo/getList", { businessIdList: [row.id] })
      .then((res) => {
        if (res[row.id] && res[row.id].length > 0) {
          fileList.value = res[row.id].map((item) => {
            return {
              raw: item,
              name: item.fileName,
              url: item.fileUrl,
            };
          });
        }
      });
    res.invoiceDetailsList = res.invoiceDetailsVoList.map((item) => {
      return {
        code: item.purchaseCode,
        purchaseId: item.purchaseId,
        amount: item.purchaseAmount,
        sumInvoiceMoney: item.sumMoney,
        money: item.money,
      };
    });
    if (res.type) {
      res.type = res.type + "";
    }
    formData.data = res;
    delete formData.data.invoiceDetailsVoList;
    loadingDialog.value = false;
  });
  dialogVisible.value = true;
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
