<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="'90%'"
    :visible="visible"
    :confirm-loading="loading"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑开票' : '添加开票'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      :label-col="{ md: { span: 4 }, sm: { span: 4 }, xs: { span: 4 } }"
      :label-align="'left'"
      :wrapper-col="{ md: { span: 24 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-card title="填报人信息" :bordered="false">
        <a-row :gutter="16">
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="填报人">
              <a-input disabled v-model:value="loginUser.username" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" :xs="24">
            <a-form-item label="填报时间">
              <a-input disabled v-model:value="now" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="合同信息" :bordered="false">
        <a-row :gutter="16">
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="合同编号" v-bind="validateInfos.contractId">
              <TowerContractSelectModel
                :placeholder="`请选择合同`"
                v-model:value="form.contractNumber"
                @done="chooseContract"
              />
            </a-form-item>
            <a-form-item label="承租单位">
              <p style="margin: 0">{{ form.customerName }}</p>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="签订日期">
              <p style="margin: 0">{{ form.signDate }}</p>
            </a-form-item>
            <a-form-item label="租赁单位">
              <p style="margin: 0">{{ form.companyName }}</p>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="项目名称">
              <p style="margin: 0">{{ form.projectName }}</p>
            </a-form-item>
            <a-form-item label="累计开票金额">
              <p style="margin: 0">{{ form.totalInvoicingAmount }}</p>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card title="开票信息" :bordered="false">
        <a-row :gutter="16">
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="开票日期" v-bind="validateInfos.invoicingDate">
              <a-date-picker
                class="ele-fluid"
                placeholder="请选择开票日期"
                v-model:value="form.invoicingDate"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-item>
            <a-form-item label="开票金额" v-bind="validateInfos.invoicingAmount">
              <a-input v-model:value="form.invoicingAmount" placeholder="请输入开票金额" type="number">
                <template #addonAfter>元</template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="开票单位" v-bind="validateInfos.invoicingCompany">
              <SelectCompany
                :placeholder="`请选择开票单位`"
                v-model:value="form.invoicingCompany"
                @done="chooseCompany"
              />
            </a-form-item>
            <a-form-item label="发票编号">
              <a-input v-model:value="form.invoicingNo" placeholder="请输入发票编号" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="申请人">
              <a-input v-model:value="form.requestName" placeholder="请输入申请人" />
            </a-form-item>
            <a-form-item label="登记人" v-bind="validateInfos.signName">
              <UserChoose @select="selectSignName" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="备注" :label-col="{ md: { span: 1 }, sm: { span: 1 }, xs: { span: 1 } }">
          <a-input v-model:value="form.remark" placeholder="请输入备注说明" />
        </a-form-item>
        <a-form-item label="附件" name="parentId">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            action="https://file.wsdns.cn/api/file/image"
            :headers="{ Authorization: token }"
            @change="onFile"
          >
            <a-button>
              <upload-outlined />
              上传
            </a-button>
          </a-upload>
        </a-form-item>
      </a-card>
      <a-card title="结算单分摊">
        <a-button @click.native="showSelectSettle = true" type="primary" :disabled="!form.contractId">新增
        </a-button>
        <Table :data-source="settleList" />
      </a-card>
    </a-form>
  </ele-modal>
  <ele-modal
    :width="'80%'"
    :visible="showSelectSettle"
    :maskClosable="false"
    title="选择结算单"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="showSelectSettle"
    @cancel="showSelectSettle = false"
    @ok="showSelectSettle = false"
  >
    <a-row :gutter="16">
      <a-col :span="6">结算状态</a-col>
      <a-col :span="6">结算单号</a-col>
      <a-col :span="6">本期结算金额</a-col>
      <a-col :span="6">操作</a-col>
    </a-row>
    <a-row :gutter="16" class="my-05" v-for="(item, index) in contractSettleList" :key="index">
      <a-col :span="6">{{ SETTLE_STATUS_LIST[item.status] }}</a-col>
      <a-col :span="6">{{ item.settleNo }}</a-col>
      <a-col :span="6">{{ item.totalAmount }}</a-col>
      <a-col :span="6">
        <a-button type="link" @click.native="selectSettle(item)">选择</a-button>
      </a-col>
    </a-row>
  </ele-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from "vue";
import { Form, message } from "ant-design-vue";
import { assignObject, EleProTable } from "ele-admin-pro";
import { useUserStore } from "@/store/modules/user";
import dayjs from "dayjs";
import { Contract } from "@/api/tower/contract/model";
import Table from "./table.vue";
import { Invoicing } from "@/api/tower/invoicing/model";
import { addInvoicing, updateInvoicing } from "@/api/tower/invoicing";
import { Company } from "@/api/system/company/model";
import { User } from "@/api/user/model";
import { TOKEN_STORE_NAME } from "@/config/setting";
import { UploadOutlined } from "@ant-design/icons-vue";
import { Settle, SETTLE_STATUS_LIST } from "@/api/tower/settle/model";
import { listSettle } from "@/api/tower/settle";
import { InvoicingSettle } from "@/api/tower/invoicingSettle/model";
import { addBatchInvoicingSettle } from "@/api/tower/invoicingSettle";

const userStore = useUserStore();
const token = localStorage.getItem(TOKEN_STORE_NAME);
// 当前用户信息
const loginUser = computed(() => userStore.info ?? {});

const now = dayjs().format("YYYY-MM-DD HH:mm:ss");

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: Invoicing | null;
}>();

const emit = defineEmits<{
  (e: "done"): void;
  (e: "update:visible", visible: boolean): void;
}>();

// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
const activeKey = ref(0);

const contractSettleList = ref<Settle[]>([]);
const getContractSettleList = async contractId => {
  contractSettleList.value = await listSettle({ contractId });
};

const showSelectSettle = ref(false);
const selectSettle = (item: Settle) => {
  settleList.value.push({
    invoicingId: null,
    settleNumber: item.settleNo,
    startDate: item.startDate,
    settleAmount: item.totalAmount
  });
  showSelectSettle.value = false;
};
const settleList = ref<InvoicingSettle[]>([]);

const chooseContract = (res: Contract) => {
  form.contractNumber = res.contactNumber;
  form.contractId = res.contractId;
  form.companyName = res.companyName;
  form.customerName = res.customerName;
  form.signDate = res.signDate;
  form.projectName = res.projectName;
  getContractSettleList(res.contractId);
};

const chooseCompany = ({ companyName }: Company) => {
  form.invoicingCompany = companyName;
};

const selectSignName = ({ nickname }: User) => {
  form.signName = nickname;
};

const fileList = ref<FileItem[]>([]);

interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: Response;
  thumbUrl?: string;
  downloadUrl?: string;
  url: string;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}

const onFile = (info: FileInfo) => {
  let resFileList = [...info.fileList];
  fileList.value = resFileList.map((file) => {
    if (file.response) {
      file.url = file.response.url;
    }
    return file;
  });
  form.fileList = JSON.stringify(fileList.value);
};

const form = reactive<Invoicing>({
  invoicingId: "",
  contractId: "",
  contractNumber: "",
  signDate: "",
  projectName: "",
  customerName: "",
  companyName: "",
  invoicingDate: "",
  invoicingCompany: "",
  invoicingAmount: "",
  fileList: "[]",
  remark: "",
  userId: loginUser.value.userId,
  totalInvoicingAmount: "",
  signName: loginUser.value.username,
  requestName: ""
});

/* 更新visible */
const updateVisible = (value: boolean) => {
  emit("update:visible", value);
};

// 表单验证规则
const rules = reactive({
  contractId: [
    {
      required: true,
      message: "请选择合同",
      trigger: "blur"
    }
  ],
  invoicingAmount: [
    {
      required: true,
      message: "请输入开票金额",
      trigger: "blur"
    }
  ],
  invoicingCompany: [
    {
      required: true,
      message: "请选择开票单位",
      trigger: "blur"
    }
  ],
  invoicingDate: [
    {
      required: true,
      message: "请选择开票日期",
      trigger: "blur"
    }
  ],
  signName: [
    {
      required: true,
      message: "请选择登记人员",
      trigger: "blur"
    }
  ]

});
const { resetFields, validate, validateInfos } = useForm(form, rules);

/* 保存编辑 */
const save = () => {
  validate()
    .then(async () => {
      loading.value = true;
      const data = {
        ...form
      };
      const saveOrUpdate = isUpdate.value ? updateInvoicing : addInvoicing;
      const res = await saveOrUpdate(data).catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
      if (settleList.value.length > 0) {
        const invoicingId = res?.data;
        settleList.value.forEach((item, index) => {
          settleList.value[index].invoicingId = invoicingId;
        });
        await addBatchInvoicingSettle(settleList.value);
      }
      message.success(res?.message);
      updateVisible(false);
      emit("done");
    })
    .catch(() => {
    });
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      if (props.data) {
        loading.value = false;
        assignObject(form, props.data);
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
      }
    } else {
      resetFields();
    }
  }
);
</script>
<style lang="less">
.title {
  font-weight: bold;
  font-size: 1.1rem;
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdfe6;
  color: #494949;
  margin-bottom: 10px;
}
</style>
