<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="'90%'"
    :visible="visible"
    :confirm-loading="loading"
    :maskClosable="false"
    :maxable="maxable"
    :title="'合同结算设置'"
    :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-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="结算方式">
            <a-select placeholder="必选项" style="width: 250px" size="small"
                      v-model:value="contract.settleMethod">
              <a-select-option v-for="(item, index) in ContractSettleMethod" :key="index" :value="index">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="[0, 3].indexOf(contract.settleMethod) > -1">
          <span>每月</span>
          <a-select placeholder="必选项" style="width: 250px" size="small"
                    v-model:value="contract.extendMonthDate">
            <a-select-option v-for="item in dateList" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
          <span>号</span>
          <span class="ml-05">至下月</span>
          <span class="ml-05" v-if="contract.extendMonthDate">{{ contract.extendMonthDate - 1 }}号</span>
        </a-col>
      </a-row>
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane :key="0" tab="结算规则设置">
          <template #default>
            <a-button type="primary" @click.native="showSelectEquip = true">添加结算设备</a-button>
            <a-table ref="contractEquipmentSettleTableRef"
                     row-key="contractSettleId" :dataSource="settleEquipmentList" :columns="equipmentColumns">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'rentMonth'">
                  <a-input v-model:value="record.rentMonth" type="number" />
                </template>
                <template v-if="column.key === 'rentAmount'">
                  <a-input v-model:value="record.rentAmount" type="number" />
                </template>
                <template v-if="column.key === 'rentAmountSum'">
                  <span>{{ record.rentMonth * record.rentAmount }}</span>
                </template>
                <template v-if="column.key === 'inOutAmount'">
                  <a-input v-model:value="record.inOutAmount" type="number" />
                </template>
                <template v-if="column.key === 'workerAmount'">
                  <a-input v-model:value="record.workerAmount" type="number" />
                </template>
                <template v-if="column.key === 'workerAmountSum'">
                  <span>{{ record.rentMonth * record.workerAmount }}</span>
                </template>
                <template v-if="column.key === 'otherAmountCalMode'">
                  <a-select style="width: 100px" size="small"
                            v-model:value="record.otherAmountCalMode">
                    <a-select-option :value="0">按月</a-select-option>
                    <a-select-option :value="1">一次</a-select-option>
                  </a-select>
                </template>
                <template v-if="column.key === 'otherAmount'">
                  <a-input v-model:value="record.otherAmount" type="number" />
                </template>
                <template v-if="column.key === 'preBuryAmount'">
                  <a-input v-model:value="record.preBuryAmount" type="number" />
                </template>
                <template v-if="column.key === 'remark'">
                  <a-input v-model:value="record.remark" />
                </template>
                <template v-if="column.key === 'action'">
                  <div class="flex justify-center items-center">
                    <close-circle-outlined style="font-size: 1.5rem; color: pink;cursor: pointer"
                                           @click.native="delEquipment(index)" />
                  </div>
                </template>
              </template>
              <template #summary>
                <a-table-summary-row>
                  <a-table-summary-cell>合计</a-table-summary-cell>
                  <a-table-summary-cell />
                  <a-table-summary-cell />
                  <a-table-summary-cell />
                  <a-table-summary-cell />
                  <a-table-summary-cell />
                  <a-table-summary-cell />
                  <a-table-summary-cell>
                    {{ totals.rentAmountSum }}
                  </a-table-summary-cell>
                  <a-table-summary-cell />
                  <a-table-summary-cell />
                  <a-table-summary-cell>
                    {{ totals.workerAmountSum }}
                  </a-table-summary-cell>
                  <a-table-summary-cell>
                    {{ totals.otherAmountSum }}
                  </a-table-summary-cell>
                  <a-table-summary-cell />
                </a-table-summary-row>
              </template>
            </a-table>
          </template>
        </a-tab-pane>
        <a-tab-pane :key="1" tab="结算周期设置">
          <template #default>
            <a-button type="primary" @click.native="addRule">新增</a-button>
            <a-table ref="contractRuleSettleTableRef"
                     row-key="contractSettleId" :dataSource="settleRuleList" :columns="ruleColumns">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'startDate'">
                  <a-date-picker
                    class="ele-fluid"
                    placeholder="请选择开始日期"
                    v-model:value="record.startDate"
                    valueFormat="YYYY-MM-DD"
                  />
                </template>
                <template v-if="column.key === 'endDate'">
                  <a-date-picker
                    class="ele-fluid"
                    placeholder="请选择结束日期"
                    v-model:value="record.endDate"
                    valueFormat="YYYY-MM-DD"
                  />
                </template>
                <template v-if="column.key === 'action'">
                  <div class="flex justify-center items-center">
                    <close-circle-outlined style="font-size: 1.5rem; color: pink;cursor: pointer"
                                           @click.native="delRule(index)" />
                  </div>
                </template>
              </template>
            </a-table>
          </template>
        </a-tab-pane>
      </a-tabs>
    </a-form>
  </ele-modal>

  <SelectData
    v-model:visible="showSelectEquip"
    :data="null"
    title="选择设备"
    @done="onSelectEquip"
  />
</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 { Contract, ContractSettleMethod } from "@/api/tower/contract/model";
import dayjs from "dayjs";

import {
  PlusOutlined,
  UnorderedListOutlined,
  CloseCircleOutlined
} from "@ant-design/icons-vue";
import { TowerModel } from "@/api/tower/model/model";
import { listTowerModel } from "@/api/tower/model";
import { ContractSettleEquipment } from "@/api/tower/contractSettle/equipment/model";
import { ColumnItem } from "ele-admin-pro/es/ele-pro-table/types";
import SelectData from "@/components/TowerEquipmentModel/components/select-data.vue";
import { ContractSettleRule } from "@/api/tower/contractSettle/rule/model";
import { updateContract } from "@/api/tower/contract";
import { addBatchContractSettleEquipment, listContractSettleEquipment } from "@/api/tower/contractSettle/equipment";
import { addBatchContractSettleRule, listContractSettleRule } from "@/api/tower/contractSettle/rule";
import { TowerEquipment } from "@/api/tower/equipment/model";
import { listContractEquipment } from "@/api/tower/contractEquipment";
import { ContractEquipment } from "@/api/tower/contractEquipment/model";


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

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

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

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

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

const showSelectEquip = ref<Boolean>(false);

const onSelectEquip = (data: TowerEquipment) => {
  addEquipment(data);
};

const contract = reactive<Contract>({
  contractId: undefined,
  settleMethod: undefined,
  extendMonthDate: undefined
});

const contractEquipmentSettleTableRef = ref<InstanceType<typeof EleProTable> | null>(null);
const equipmentColumns = ref<ColumnItem[]>([
  {
    title: "序号",
    key: "index",
    width: 48,
    align: "center",
    fixed: "left",
    hideInSetting: true,
    customRender: ({ index }) => index + (contractEquipmentSettleTableRef.value?.tableIndex ?? 1)
  },
  {
    title: "设备名",
    dataIndex: "equipmentName",
    key: "equipmentName"
  },
  {
    title: "规格",
    dataIndex: "equipmentModel",
    key: "equipmentModel"
  },
  {
    title: "进场编号",
    dataIndex: "factoryNo",
    key: "factoryNo"
  },
  {
    title: "自编号",
    dataIndex: "equipmentNo",
    key: "equipmentNo"
  },
  {
    title: "计划租期(月)",
    dataIndex: "rentMonth",
    key: "rentMonth"
  },
  {
    title: "租金(元)",
    dataIndex: "rentAmount",
    key: "rentAmount"
  },
  {
    title: "租金小计(元)",
    dataIndex: "rentAmountSum",
    key: "rentAmountSum"
  },
  {
    title: "进退场费(元)",
    dataIndex: "inOutAmount",
    key: "inOutAmount"
  },
  {
    title: "劳务费用(元)",
    dataIndex: "workerAmount",
    key: "workerAmount"
  },
  {
    title: "劳务小计(元)",
    dataIndex: "workerAmountSum",
    key: "workerAmountSum"
  },
  {
    title: "其他费用(元)",
    dataIndex: "otherAmount",
    key: "otherAmount"
  },
  {
    title: "其他费用结算模式",
    dataIndex: "otherAmountCalMode",
    key: "otherAmountCalMode",
    width: 100
  },
  {
    title: "预埋费(元)",
    dataIndex: "preBuryAmount",
    key: "preBuryAmount"
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark"
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action"
  }
]);

const equipmentList = ref<ContractEquipment[]>([]);
const getEquipmentList = async () => {
  equipmentList.value = await listContractEquipment({ contractId: props.data?.contractId });
};

const settleEquipmentList = ref<ContractSettleEquipment[]>([]);
const getSettleEquipmentList = async () => {
  settleEquipmentList.value = await listContractSettleEquipment({ contractId: contract.contractId });
  if (settleEquipmentList.value.length === 0) {
    equipmentList.value.forEach(item => {
      addEquipment(item, item.planRentMonth, item.rentAmount, item.inOutAmount, item.workerAmount, item.otherAmount, item.otherAmount);
    });
  }
};

const contractEquipmentList = ref<ContractEquipment[]>([]);
const getContractEquipmentList = async () => {
  contractEquipmentList.value = await listContractEquipment({ contractId: props.data?.contractId });
  contractEquipmentList.value.forEach(data => {
    data.name = data.equipmentName
    data.model = data?.equipmentModel
    addEquipment(data);
  });
};

const addEquipment = (data, rentMonth = 0, rentAmount = 0, inOutAmount = 0, workerAmount = 0, otherAmount = 0, preBuryAmount = 0) => {
  settleEquipmentList.value = [...settleEquipmentList.value, {
    contractSettleId: 0,
    equipmentId: data.equipmentId,
    contractId: props.data?.contractId,
    equipmentName: data.name,
    equipmentModel: data.model,
    factoryNo: data.factoryNo,
    filingNo: data.filingNo,
    equipmentNo: data.equipmentNo,
    rentMonth,
    rentAmount,
    inOutAmount,
    workerAmount,
    otherAmount,
    otherAmountCalMode: 0,
    preBuryAmount,
    remark: "",
    userId: loginUser.value.userId
  }];
};

const delEquipment = index => {
  settleEquipmentList.value.splice(index, 1);
};

const contractRuleSettleTableRef = ref<InstanceType<typeof EleProTable> | null>(null);
const settleRuleList = ref<ContractSettleRule[]>([]);
const getSettleRuleList = async () => {
  settleRuleList.value = await listContractSettleRule({ contractId: contract.contractId });
};

const ruleColumns = ref<ColumnItem[]>([
  {
    title: "序号",
    key: "index",
    width: 48,
    align: "center",
    fixed: "left",
    hideInSetting: true,
    customRender: ({ index }) => index + (contractRuleSettleTableRef.value?.tableIndex ?? 1)
  },
  {
    title: "设备名",
    dataIndex: "equipmentName",
    key: "equipmentName"
  },
  {
    title: "结算开始日期",
    dataIndex: "startDate",
    key: "startDate"
  },
  {
    title: "结算结束日期",
    dataIndex: "endDate",
    key: "endDate"
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action"
  }
]);
const addRule = () => {
  settleRuleList.value.push({
    contractId: props.data?.contractId,
    startDate: "",
    endDate: ""
  });
};

const delRule = index => {
  settleRuleList.value.splice(index, 1);
};

const totals = computed(() => {
  let rentAmountSum = 0;
  let workerAmountSum = 0;
  let otherAmountSum = 0;

  settleEquipmentList.value.forEach(({ rentMonth, rentAmount, workerAmount, otherAmountCalMode, otherAmount }) => {
    rentAmountSum += rentMonth * rentAmount;
    workerAmountSum += rentMonth * workerAmount;
    if (otherAmountCalMode === 0) otherAmountSum += rentMonth * otherAmount;
    else otherAmountSum += otherAmount;
  });
  return { rentAmountSum, workerAmountSum, otherAmountSum };
});

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

/* 保存编辑 */
const save = () => {
  if (contract.settleMethod === undefined) {
    message.error("请选择结算方式");
    return;
  }
  if (settleEquipmentList.value.length === 0) {
    message.error("请至少设置一条结算规则");
    return;
  }
  if (settleRuleList.value.length === 0) {
    message.error("请至少设置一条结算周期");
    return;
  }
  for (let i = 0; i < settleRuleList.value.length; i++) {
    if (!settleRuleList.value[i].startDate) {
      message.error("请选择结算开始日期");
      return;
    }
    if (!settleRuleList.value[i].endDate) {
      message.error("请选择结算结束日期");
      return;
    }
  }
  loading.value = true;
  Promise.all([updateContract(contract), addBatchContractSettleEquipment(settleEquipmentList.value), addBatchContractSettleRule(settleRuleList.value)])
    .then(() => {
      loading.value = false;
      // message.success(res.message);
      updateVisible(false);
      emit("done");
    });
};

watch(
  () => props.visible,
  async (visible) => {
    if (visible) {
      for (let i = 2; i < 28; i++) dateList.value.push(i);
      await getEquipmentList();
      settleEquipmentList.value = [];
      if (props.data) {
        loading.value = false;
        assignObject(contract, props.data);
        await getSettleEquipmentList();
        await getSettleRuleList();
        isUpdate.value = true;
      } else {
        await getContractEquipmentList();
        isUpdate.value = false;
      }
    }
  }
);
</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>
