<!-- 用户编辑弹窗 -->
<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-form-item label="累计开票金额">
              <p style="margin: 0">{{ form.totalInvoicingAmount }}</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.totalIncomeAmount }}</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="收款单号">
              <a-input v-model:value="form.incomeNo" placeholder="请输入收款单号" />
            </a-form-item>
            <a-form-item label="收款金额" v-bind="validateInfos.amount">
              <a-input v-model:value="form.amount" placeholder="请输入收款金额" type="number">
                <template #addonAfter>元</template>
              </a-input>
            </a-form-item>
            <a-form-item label="预计收款日期">
              <a-date-picker
                class="ele-fluid"
                placeholder="请选择预计收款日期"
                v-model:value="form.expectIncomeDate"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="收款日期" v-bind="validateInfos.incomeDate">
              <a-date-picker
                class="ele-fluid"
                placeholder="请选择收款日期"
                v-model:value="form.incomeDate"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-item>
            <a-form-item label="收款类型">
              <a-select placeholder="请选择收款类型" style="width: 250px" size="small"
                        v-model:value="form.incomeType">
                <a-select-option value="直租">直租</a-select-option>
                <a-select-option value="转租">转租</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="预计收款金额">
              <a-input v-model:value="form.expectIncomeAmount" 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.incomeCompanyId">
              <SelectCustomer
                :placeholder="`请选择收款单位`"
                v-model:value="form.incomeCompanyName"
                @done="chooseIncomeCompany"
              />
            </a-form-item>
            <a-form-item label="付款单位">
              <SelectCompany
                :placeholder="`请选择付款单位`"
                v-model:value="form.payCompanyName"
                @done="choosePayCompany"
              />
            </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 } }">
          <DictSelect
            dict-code="ContractIncomeMethod"
            placeholder="请选择收款方式"
            v-model:value="form.incomeMethod"
          />
        </a-form-item>
        <a-form-item label="发票号" :label-col="{ md: { span: 1 }, sm: { span: 1 }, xs: { span: 1 } }">
          <a-input v-model:value="form.invoicingNo" placeholder="请输入发票号" />
        </a-form-item>
        <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">{{ item.equipmentName }}</a-col>
      <a-col :span="6">{{ item.equipmentModel }}</a-col>
      <a-col :span="6">{{ item.rentAmount }}</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 { 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 { addIncome, updateIncome } from "@/api/tower/income";
import { Income } from "@/api/tower/income/model";
import { IncomeEquipment } from "@/api/tower/incomeEquipment/model";
import { addBatchIncomeEquipment } from "@/api/tower/incomeEquipment";
import { ContractSettleEquipment } from "@/api/tower/contractSettle/equipment/model";
import { listContractEquipment } from "@/api/tower/contractEquipment";
import { ContractEquipment } from "@/api/tower/contractEquipment/model";
import { Customer } from "@/api/oa/customer/model";

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?: Income | 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<ContractEquipment[]>([]);
const getContractSettleList = async contractId => {
  contractSettleList.value = await listContractEquipment({ contractId });
};

const showSelectSettle = ref(false);
const settleList = ref<IncomeEquipment[]>([]);
const selectSettle = (item: ContractEquipment) => {
  settleList.value.push({
    incomeEquipmentId: null,
    incomeId: null,
    equipmentId: item.equipmentId,
    equipmentName: item.equipmentName,
    equipmentModel: item.equipmentModel,
    factoryNo: item.factoryNo,
    equipmentNo: item.equipmentNo,
    filingNo: item.filingNo,
    rentAmount: item.rentAmount,
    shareAmount: null
  });
  showSelectSettle.value = false;
};

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;
  form.totalInvoicingAmount = res.totalInvoicingAmount;
  form.totalIncomeAmount = res.totalIncomeAmount;
  getContractSettleList(res.contractId);
};

const choosePayCompany = ({ companyName, companyId }: Company) => {
  form.payCompanyId = companyId;
  form.payCompanyName = companyName;
};

const chooseIncomeCompany = ({ customerId, name }: Customer) => {
  form.incomeCompanyId = customerId;
  form.incomeCompanyName = name;
};

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<Income>({
  incomeId: "",
  contractId: "",
  contractNumber: "",
  signDate: "",
  projectName: "",
  customerName: "",
  companyName: "",
  incomeNo: `I-` + dayjs().format("YYYY-MM-DD"),
  incomeCompanyName: "",
  incomeCompanyId: "",
  payCompanyName: "",
  payCompanyId: "",
  incomeDate: "",
  amount: "",
  totalIncomeAmount: "",
  totalInvoicingAmount: "",
  fileList: "[]",
  remark: "",
  userId: loginUser.value.userId,
  signName: loginUser.value.username
});

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

// 表单验证规则
const rules = reactive({
  contractId: [
    {
      required: true,
      message: "请选择合同",
      trigger: "blur"
    }
  ],
  amount: [
    {
      required: true,
      message: "请输入收款金额",
      trigger: "blur"
    }
  ],
  incomeDate: [
    {
      required: true,
      message: "请输入收款日期",
      trigger: "blur"
    }
  ],
  incomeCompanyId: [
    {
      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 ? updateIncome : addIncome;
      const res = await saveOrUpdate(data).catch((e) => {
        message.error(e.message);
      });
      loading.value = false;
      if (settleList.value.length > 0) {
        const incomeId = res?.data;
        settleList.value.forEach((item, index) => {
          settleList.value[index].incomeId = incomeId;
        });
        await addBatchIncomeEquipment(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>
