<!-- 用户编辑弹窗 -->
<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: 6 }, sm: { span: 20 }, xs: { span: 24 } }"
      :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.contactNumber"
                @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-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.amountWithTax">
              <DictSelect
                dict-code="PropertyCompany"
                placeholder="请选择产权单位"
                v-model:value="form.propertyCompany"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="结算日期">
              <a-date-picker
                class="ele-fluid"
                placeholder="请选择结束日期"
                v-model:value="form.settleDate"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="本期结算金额">
              <a-input v-model:value="form.settleAmount" disabled placeholder="自动计算">
                <template #suffix>元</template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="备注">
          <a-input v-model:value="form.remark" placeholder="请输入备注说明" />
        </a-form-item>
      </a-card>
      <a-card title="结算清单">
        <a-button @click.native="showSelectEquipment = true" type="primary"
                  :disabled="!form.contractId || settleList.length === contractEquipmentList.length">新增
        </a-button>
        <Table :data-source="settleList" @total="setTotal" />
      </a-card>
    </a-form>
  </ele-modal>
  <ele-modal
    :width="'80%'"
    :visible="showSelectEquipment"
    :maskClosable="false"
    title="选择设备"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="showSelectEquipment"
    @cancel="showSelectEquipment = false"
    @ok="showSelectEquipment = false"
  >
    <a-row :gutter="16">
      <a-col :span="8">设备名称</a-col>
      <a-col :span="8">设备型号</a-col>
      <a-col :span="8">操作</a-col>
    </a-row>
    <a-row :gutter="16" class="my-05" v-for="(item, index) in contractEquipmentList" :key="index">
      <a-col :span="8">{{ item.equipmentName }}</a-col>
      <a-col :span="8">{{ item.equipmentModel }}</a-col>
      <a-col :span="8">
        <a-button type="link" @click.native="selectEquipment(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 { addLending, updateLending } from "@/api/tower/lending";
import { Lending } from "@/api/tower/lending/model";
import { Contract } from "@/api/tower/contract/model";
import { ContractSettleEquipment } from "@/api/tower/contractSettle/equipment/model";
import { listContractSettleEquipment } from "@/api/tower/contractSettle/equipment";
import Table from "@/views/tower/lending/components/table.vue";
import { LendingSettle } from "@/api/tower/lendingSettle/model";
import { addBatchLendingSettle, listLendingSettle } from "@/api/tower/lendingSettle";

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

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

const showSelectEquipment = ref(false);
const contractEquipmentList = ref<ContractSettleEquipment[]>([]);
const settleList = ref<LendingSettle[]>([]);

const getSettleList = async () => {
  settleList.value = await listLendingSettle({lendingId: form.lendingId})
}

const getContractEquipmentList = async () => {
  const contractEquipmentParam = <ContractSettleEquipment>{
    contractId: form.contractId
  };
  contractEquipmentList.value = await listContractSettleEquipment(contractEquipmentParam);
  settleList.value = [];
  contractEquipmentList.value.forEach(item => {
    addSettleList(item);
  });
};

const selectEquipment = item => {
  addSettleList(item);
  showSelectEquipment.value = false;
};

const addSettleList = item => {
  settleList.value.push({
    equipmentId: item.equipmentId,
    lendingId: form.lendingId,
    equipmentName: item.equipmentName,
    equipmentModel: item.equipmentModel,
    equipmentNo: item.equipmentNo,
    lendingPath: null,
    coopWay: null,
    startDate: null,
    stopDate: null,
    calDay: null,
    daysInMonth: null,
    monthRentAmount: null,
    shouldPayRentAmount: null,
    dailyRentAmount: null,
    shouldSupplementAmount: null,
    shouldDeductionAmount: null,
    paidAmount: null,
    taxRate: null,
    taxAmount: null,
    totalAmountWithTax: null,
    remark: "",
    userId: loginUser.value.userId
  });
};

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: Lending | 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 chooseContract = (res: Contract) => {
  form.contactNumber = res.contactNumber;
  form.contractId = res.contractId;
  form.companyName = res.companyName;
  form.customerName = res.customerName;
  form.signDate = res.signDate;
  form.projectName = res.projectName;
  getContractEquipmentList();
};

const form = reactive<Lending>({
  lendingId: "",
  contractId: "",
  contactNumber: "",
  signDate: "",
  projectName: "",
  customerName: "",
  companyName: "",
  propertyCompany: "",
  settleDate: "",
  settleAmount: "",
  fileList: "",
  remark: "",
  userId: loginUser.value.userId
});

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

// 表单验证规则
const rules = reactive({
  contractId: [
    {
      required: true,
      message: "请选择合同",
      trigger: "blur"
    }
  ],
  propertyCompany: [
    {
      required: true,
      message: "请选择产权单位",
      trigger: "blur"
    }
  ],
  settleDate: [
    {
      required: true,
      message: "请选择结算日期",
      trigger: "blur"
    }
  ]
});
const { resetFields, validate, validateInfos } = useForm(form, rules);

const setTotal = total => {
  form.settleAmount = total;
};
/* 保存编辑 */
const save = () => {
  validate()
    .then(async () => {
      loading.value = true;
      const data = {
        ...form
      };
      if (settleList.value.length === 0) {
        message.error("请选择结算设备");
        return;
      }
      const saveOrUpdate = isUpdate.value ? updateLending : addLending;
      const res = await saveOrUpdate(data).catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
      const lendingId = res?.data;
      settleList.value.forEach((item, index) => {
        settleList.value[index].lendingId = lendingId;
      });
      await addBatchLendingSettle(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;
        getSettleList()
      } 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>
