<!-- 用户编辑弹窗 -->
<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="projectName"
                @done="chooseContract"
              />
            </a-form-item>
            <a-form-item label="结算单号" v-bind="validateInfos.settleNo">
              <a-input v-model:value="form.settleNo" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" :xs="24">
            <a-form-item label="本期开始日期"  v-bind="validateInfos.dateRange">
              <a-range-picker v-model:value="dateRange" picker="month" />
            </a-form-item>
            <!--            <a-form-item label="本期开始日期" v-bind="validateInfos.startDate">-->
            <!--              <a-date-picker-->
            <!--                class="ele-fluid"-->
            <!--                placeholder="请选择开始日期"-->
            <!--                v-model:value="form.startDate"-->
            <!--                valueFormat="YYYY-MM-DD"-->
            <!--              />-->
            <!--            </a-form-item>-->
            <!--            <a-form-item label="结算方式">-->
            <!--              <a-select placeholder="请先选择项目" style="width: 250px" size="small" :disabled="!form.contractId"-->
            <!--                        v-model:value="form.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 :md="8" :sm="24" :xs="24">-->
          <!--            <a-form-item label="本期结束日期" v-bind="validateInfos.endDate">-->
          <!--              <a-date-picker-->
          <!--                class="ele-fluid"-->
          <!--                placeholder="请选择开始日期"-->
          <!--                v-model:value="form.endDate"-->
          <!--                valueFormat="YYYY-MM-DD"-->
          <!--              />-->
          <!--            </a-form-item>-->
          <!--            <div v-if="[0, 3].indexOf(form.settleMethod) > -1">-->
          <!--              <span>每月</span>-->
          <!--              <a-select placeholder="必选项" style="width: 250px" size="small"-->
          <!--                        v-model:value="form.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="form.extendMonthDate">{{ form.extendMonthDate - 1 }}号</span>-->
          <!--            </div>-->
          <!--          </a-col>-->
        </a-row>
      </a-card>
    </a-form>
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane :key="0" tab="租金结算">
        <template #default v-if="activeKey === 0">
          <div class="flex justify-between items-center">
            <div class="flex-1">
              <a-button :disabled="!form.contractId || contractEquipmentList.length === 0" type="primary"
                        @click.native="doShowSelectEquipment(0)">
                新增
              </a-button>
              <!--              <a-button class="mx-05" :disabled="!form.contractId || contractEquipmentList.length === 0"-->
              <!--                        type="primary" @click.native="oneKetAddEquipment(0)">一键加载结算设备-->
              <!--              </a-button>-->
              <!--              <a-button :disabled="!form.startDate || !form.startDate" type="primary"-->
              <!--                        @click.native="onyKeyAsyncDate(0)">同步结算起止日期-->
              <!--              </a-button>-->
            </div>
            <a-input style="width: 300px" v-model:value="taxRate[0]" @change="changeTaxRate($event, 0)">
              <template #prefix>税率</template>
              <template #addonAfter>%</template>
            </a-input>
          </div>
          <table0 :data-source="dataSource[0]" />
        </template>
      </a-tab-pane>
      <a-tab-pane :key="1" tab="进退场费">
        <template #default v-if="activeKey === 1">
          <div class="flex justify-between items-center">
            <div class="flex-1">
              <a-button :disabled="!form.contractId || contractEquipmentList.length === 0" type="primary"
                        @click.native="doShowSelectEquipment(1)">
                选择结算设备
              </a-button>
              <a-button class="mx-05" :disabled="!form.contractId || contractEquipmentList.length === 0"
                        type="primary" @click.native="oneKetAddEquipment(1)">一键加载结算设备
              </a-button>
              <a-button :disabled="!form.startDate || !form.startDate" type="primary"
                        @click.native="onyKeyAsyncDate(1)">同步结算起止日期
              </a-button>
            </div>
            <a-input style="width: 300px" v-model:value="taxRate[1]" @change="changeTaxRate($event, 1)">
              <template #prefix>税率</template>
              <template #addonAfter>%</template>
            </a-input>
          </div>
          <table1 :data-source="dataSource[1]" />
        </template>
      </a-tab-pane>
      <a-tab-pane :key="2" tab="操作人员工资结算">
        <template #default>
          <div class="flex justify-between items-center">
            <div class="flex-1">
              <a-button :disabled="!form.contractId || contractEquipmentList.length === 0" type="primary"
                        @click.native="doShowSelectEquipment(2)">
                选择结算设备
              </a-button>
              <a-button class="mx-05" :disabled="!form.contractId || contractEquipmentList.length === 0"
                        type="primary" @click.native="oneKetAddEquipment(2)">一键加载结算设备
              </a-button>
              <!--              <a-button :disabled="!form.startDate || !form.startDate" type="primary"-->
              <!--                        @click.native="onyKeyAsyncDate(2)">同步结算起止日期-->
              <!--              </a-button>-->
            </div>
            <a-input style="width: 300px" v-model:value="taxRate[2]" @change="changeTaxRate($event, 2)">
              <template #prefix>税率</template>
              <template #addonAfter>%</template>
            </a-input>
          </div>
          <table2 :data-source="dataSource[2]" v-if="activeKey === 2" />
        </template>
      </a-tab-pane>
      <a-tab-pane :key="3" tab="其他费用清单">
        <template #default v-if="activeKey === 3">
          <div class="flex justify-between items-center">
            <div class="flex-1">
              <a-button :disabled="!form.contractId || contractEquipmentList.length === 0" type="primary"
                        @click.native="doShowSelectEquipment(3)">
                选择结算设备
              </a-button>
              <a-button class="mx-05" :disabled="!form.contractId || contractEquipmentList.length === 0"
                        type="primary" @click.native="oneKetAddEquipment(3)">一键加载结算设备
              </a-button>
              <!--              <a-button :disabled="!form.startDate || !form.startDate" type="primary"-->
              <!--                        @click.native="onyKeyAsyncDate(3)">同步结算起止日期-->
              <!--              </a-button>-->
            </div>
            <a-input style="width: 300px" v-model:value="taxRate[3]" @change="changeTaxRate($event, 3)">
              <template #prefix>税率</template>
              <template #addonAfter>%</template>
            </a-input>
          </div>
          <table3 :data-source="dataSource[3]" />
        </template>
      </a-tab-pane>
      <a-tab-pane :key="4" tab="扣除项">
        <template #default v-if="activeKey === 4">
          <div class="flex justify-between items-center">
            <div class="flex-1">
              <a-button :disabled="!form.contractId || contractEquipmentList.length === 0" type="primary"
                        @click.native="doShowSelectEquipment(4)">
                选择结算设备
              </a-button>
              <a-button class="mx-05" :disabled="!form.contractId || contractEquipmentList.length === 0"
                        type="primary" @click.native="oneKetAddEquipment(4)">一键加载结算设备
              </a-button>
              <!--              <a-button :disabled="!form.startDate || !form.startDate" type="primary"-->
              <!--                        @click.native="onyKeyAsyncDate(4)">同步结算起止日期-->
              <!--              </a-button>-->
            </div>
            <a-input style="width: 300px" v-model:value="taxRate[4]" @change="changeTaxRate($event, 4)">
              <template #prefix>税率</template>
              <template #addonAfter>%</template>
            </a-input>
          </div>
          <table4 :data-source="dataSource[4]" />
        </template>
      </a-tab-pane>
    </a-tabs>
  </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 { Contract, ContractSettleMethod } from "@/api/tower/contract/model";
import dayjs, { Dayjs } from "dayjs";

import { Settle } from "@/api/tower/settle/model";
import { addSettle, updateSettle } from "@/api/tower/settle";
import { ContractEquipment, ContractEquipmentParam } from "@/api/tower/contractEquipment/model";
import { SettleDetail } from "@/api/tower/settleDetail/model";
import Table0 from "@/views/tower/settle/components/editTable/table0.vue";
import { listContractSettleEquipment } from "@/api/tower/contractSettle/equipment";
import { ContractSettleEquipment } from "@/api/tower/contractSettle/equipment/model";
import Table1 from "@/views/tower/settle/components/editTable/table1.vue";
import Table2 from "@/views/tower/settle/components/editTable/table2.vue";
import Table3 from "@/views/tower/settle/components/editTable/table3.vue";
import Table4 from "@/views/tower/settle/components/editTable/table4.vue";
import { addBatchSettleDetail, addSettleDetail, listSettleDetail } from "@/api/tower/settleDetail";

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

const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
const dateList = ref<number[]>([]);

// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 修改回显的数据
  data?: Settle | 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 form = reactive<Settle>({
  settleId: undefined,
  settleNo: `JS-${dayjs().format("YYYY-MM-DD")}`,
  status: undefined,
  contractId: undefined,
  startDate: "",
  endDate: "",
  settleMethod: undefined,
  extendMonthDate: undefined,
  userId: loginUser.value.userId
});

const taxRate = ref([0, 0, 0, 0, 0]);

const dataSource = ref<Array<SettleDetail>[]>([
  <SettleDetail[]>[],
  <SettleDetail[]>[],
  <SettleDetail[]>[],
  <SettleDetail[]>[],
  <SettleDetail[]>[]
]);

const getDataSource = async () => {
  const res = await listSettleDetail({ settleId: form.settleId });
  dataSource.value.forEach((item, index) => {
    dataSource.value[index] = <SettleDetail[]>[];
  });
  res.forEach(item => {
    if ((item.type === 0 || item.type === 2)) {
      const days = dayjs(item.endDate).diff(dayjs(item.startDate), "day");
      item = { ...item, ...{ days } };
    }
    dataSource.value[item.type].push(item);
    taxRate.value[item.type] = parseFloat(item.taxRate);
  });
};

const contractEquipmentList = ref<ContractSettleEquipment[]>([]);
const getContractEquipmentList = async () => {
  const contractEquipmentParam = <ContractSettleEquipment>{
    contractId: form.contractId
  };
  contractEquipmentList.value = await listContractSettleEquipment(contractEquipmentParam);
};
/* 更新visible */
const updateVisible = (value: boolean) => {
  emit("update:visible", value);
};

// 表单验证规则
const rules = reactive({
  contractId: [
    {
      required: true,
      message: "请选择项目",
      trigger: "blur"
    }
  ],
  // startDate: [
  //   {
  //     required: true,
  //     message: "请选择开始日期",
  //     trigger: "blur"
  //   }
  // ],
  // endDate: [
  //   {
  //     required: true,
  //     message: "请选择结束日期",
  //     trigger: "blur"
  //   }
  // ],
  settleNo: [
    {
      required: true,
      message: "请输入结算单号",
      trigger: "blur"
    }
  ],
   dateRange: [
    {
      required: true,
      message: "请选择所属期间",
      trigger: "blur"
    }
  ],

});

const projectName = ref<string | undefined>("");
const chooseContract = (res: Contract) => {
  projectName.value = res.projectName;
  form.contractId = res.contractId;
  form.settleMethod = res.settleMethod;
  form.startDate = res.startDate;
  form.endDate = res.endDate;
  getContractEquipmentList();
};

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

const dateRange = ref<[Dayjs, Dayjs] | [string, string]>()

/* 保存编辑 */
const save = () => {
  validate()
    .then(async () => {
      loading.value = true;
      const data = {
        ...form
      };
      let totalAmount = 0;
      dataSource.value.forEach(data => {
        data.forEach(item => {
          if ((item.type === 0 || item.type === 2) && item.dailyAmount && item.days)
            totalAmount += (item.dailyAmount * item.day) + (item.monthAmount * item.month);
          else if ((item.type === 1 || item.type === 3) && item.singleAmount && item.num)
            totalAmount += item.singleAmount * item.num;
          else if (item.type === 4 && item.singleAmount && item.num)
            totalAmount -= item.singleAmount * item.num;
        });
      });
      data.totalAmount = totalAmount;
      // 转字符串
      const saveOrUpdate = isUpdate.value ? updateSettle : addSettle;
      const res = await saveOrUpdate(data).catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
      const settleId = res.data;
      const detailList = <SettleDetail[]>[];
      dataSource.value.forEach((data, dataIndex) => {
        data.forEach((item, index) => {
          item.settleId = settleId;
          detailList.push(item);
        });
      });
      await addBatchSettleDetail(detailList);
      loading.value = false;
      message.success(res.message);
      updateVisible(false);
      emit("done");

    })
    .catch(() => {
    });
};

const showSelectEquipment = ref<Boolean>(false);
const selectEquipmentType = ref<number>(0);
const doShowSelectEquipment = (index: number) => {
  selectEquipmentType.value = index;
  showSelectEquipment.value = true;
};
const selectEquipment = (data: ContractSettleEquipment) => {
  addDataSource(data, selectEquipmentType.value);
  showSelectEquipment.value = false;
};

const oneKetAddEquipment = index => {
  contractEquipmentList.value.forEach(data => {
    addDataSource(data, index);
  });
};

const addDataSource = (data: ContractSettleEquipment, index) => {
  let days = 0;
  if (form.startDate && form.endDate) days = dayjs(form.endDate).diff(dayjs(form.startDate), "day");
  dataSource.value[index].push({
    settleDetailId: 0,
    settleId: 0,
    type: index,
    settleCostType: index === 1 ? "进退场费" : "",
    equipmentName: data.equipmentName,
    equipmentModel: data.equipmentModel,
    // factoryNo: data.factoryNo,
    startDate: form.startDate ?? "",
    endDate: form.endDate ?? "",
    monthAmount: data.rentAmount ?? 0,
    taxRate: taxRate.value[index],
    singleAmount: 0,
    num: 0,
    unit: "",
    remark: "",
    userId: loginUser.value.userId,
    days,
    dailyAmount: 0,
    inDate: "",
    outDate: "",
    payRate: 100
  });
};

const onyKeyAsyncDate = index => {
  dataSource.value[index].forEach((item, dataIndex) => {
    dataSource.value[index][dataIndex].startDate = form.startDate;
    dataSource.value[index][dataIndex].endDate = form.endDate;
  });
};

const changeTaxRate = ({ target: { value } }, index) => {
  dataSource.value[index].forEach((item, dataIndex) => {
    dataSource.value[index][dataIndex].taxRate = parseFloat(value);
  });
};

watch(
  () => props.visible,
  (visible) => {
    for (let i = 2; i < 28; i++) dateList.value.push(i);
    if (visible) {
      if (props.data) {
        loading.value = false;
        assignObject(form, props.data);
        isUpdate.value = true;
        projectName.value = props.data.projectName;
        getDataSource();
        getContractEquipmentList();
      } else {
        isUpdate.value = false;
      }
    } else {
      projectName.value = "";
      dataSource.value = [[], [], [], [], []];
      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>
