<!-- 用户编辑弹窗 -->
<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-form-item label="结算总金额">
              <p style="margin: 0">{{ form.totalSettleAmount }}</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="结算单位" v-bind="validateInfos.settleCompanyId">
              <SelectCompany
                :placeholder="`请选择结算单位`"
                v-model:value="form.settleCompanyName"
                @done="chooseCompany"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="登记人" v-bind="validateInfos.signName">
              <UserChoose @select="selectSignName" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="登记日期" v-bind="validateInfos.signDate">
              <a-date-picker
                class="ele-fluid"
                placeholder="请选择登记日期"
                v-model:value="form.signDate"
                valueFormat="YYYY-MM-DD"
              />
            </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="showSelectItem = true" type="primary" :disabled="!form.contractId">新增
        </a-button>
        <Table :data-source="lostList" />
      </a-card>
    </a-form>
  </ele-modal>
  <ele-modal
    :width="'80%'"
    :visible="showSelectItem"
    :maskClosable="false"
    title="选择配件"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="showSelectItem"
    @cancel="showSelectItem = false"
    @ok="showSelectItem = false"
  >
    <a-row :gutter="16">
      <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 categoryList" :key="index">
      <a-col :span="6">{{ item.title }}</a-col>
      <a-col :span="6">
        <a-button type="link" @click.native="selectItem(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 { FinalSettle } from "@/api/tower/finalSettle/model";
import { Category } from "@/api/goods/category/model";
import { addFinalSettle, updateFinalSettle } from "@/api/tower/finalSettle";
import { FinalSettleLost } from "@/api/tower/finalSettleLost/model";
import { addBatchFinalSettleLost } from "@/api/tower/finalSettleLost";
import { listCategory } from "@/api/goods/category";


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?: FinalSettle | 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 categoryList = ref<Category[]>([]);
const getCategoryList = async () => {
  categoryList.value = await listCategory({ parentId: -1 });
};

const showSelectItem = ref(false);
const lostList = ref<FinalSettleLost[]>([]);
const selectItem = (item: Category) => {
  lostList.value.push({
    finalSettleLostId: null,
    finalSettleId: null,
    itemId: item.categoryId,
    amount: null,
    num: null,
    itemName: item.title,
    total: null
  });
  showSelectItem.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;
};

const chooseCompany = ({ companyName, companyId }: Company) => {
  form.settleCompanyId = companyId;
  form.settleCompanyName = 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<FinalSettle>({
  contractFinalSettleId: null,
  contractId: null,
  settleCompanyId: "",
  fileList: "[]",
  signName: "",
  signDate: dayjs().format("YYYY-MM-DD"),
  remark: "",
  settleCompanyName: "",
  contractNumber: "",
  companyName: "",
  customerName: "",
  projectName: "",
  totalInvoicingAmount: "",
  totalIncomeAmount: "",
  totalSettleAmount: ""
});

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

// 表单验证规则
const rules = reactive({
  contractId: [
    {
      required: true,
      message: "请选择合同",
      trigger: "blur"
    }
  ],
  settleCompanyId: [
    {
      required: true,
      message: "请选择结算单位",
      trigger: "blur"
    }
  ],
  signDate: [
    {
      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 ? updateFinalSettle : addFinalSettle;
      const res = await saveOrUpdate(data).catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
      if (lostList.value.length > 0) {
        const finalSettleId = res?.data;
        lostList.value.forEach((item, index) => {
          lostList.value[index].finalSettleId = finalSettleId;
        });
        await addBatchFinalSettleLost(lostList.value);
      }
      message.success(res?.message);
      updateVisible(false);
      emit("done");
    })
    .catch(() => {
    });
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      getCategoryList();
      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>
