<template>
  <div class="AddBuildingBox">
    <PageHeader></PageHeader>
    <div class="AddBuildingBody">
      <div class="title">基本信息</div>
      <div class="addBuildingFormBody">
        <el-form class="formBody" label-position="right" ref="formRef" :model="form" :rules="rules" label-width="130px">
          <el-form-item label="账单名称" prop="billName">
            <el-input v-model.trim="form.billName" placeholder="请输入账单名称" />
          </el-form-item>
          <el-form-item label="收费项目" prop="chargeItemId">
            <el-select v-model="form.chargeItemId" @change="(val: string) => handleChange(val, true)">
              <el-option
                :disabled="item.status === '1'"
                v-for="(item, index) in chargeitemlist"
                :key="index"
                :value="item.id"
                :label="item.itemName"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 水费，电费， 收费范围为 房屋 -->
          <el-form-item label="收费范围" prop="chargeScope" v-if="typeNamelist.includes(typeName)">
            <div>
              <div class="flex flex-row flex-items-end">
                <el-radio-group v-model="form.chargeScope">
                  <div class="flex flex-col flex-items-end">
                    <el-radio
                      :disabled="!form.chargeItemId"
                      style="margin-right: 0"
                      v-for="(item, index) in com_bill_charge_scope_house"
                      :key="index"
                      :value="item.value"
                      :label="item.label"
                    ></el-radio>
                  </div>
                </el-radio-group>
                <div style="height: 32px">
                  <el-button @click="OpenUseTablesfun('house')" link type="primary" v-if="form.chargeScope === '1'" class="ml-10px">请选择</el-button>
                </div>
              </div>
            </div>
          </el-form-item>
          <!-- 其他费用， 收费范围为 业主 -->
          <el-form-item label="收费范围" prop="chargeScope" v-else>
            <div class="flex flex-row flex-items-end">
              <el-radio-group v-model="form.chargeScope">
                <div class="flex flex-col flex-items-end">
                  <el-radio
                    style="margin-right: 0"
                    :disabled="!form.chargeItemId"
                    v-for="(item, index) in com_questionnaire_scope"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  ></el-radio>
                </div>
              </el-radio-group>
              <div style="height: 32px">
                <el-button @click="OpenUseTablesfun('user')" link type="primary" v-if="form.chargeScope === '1'" class="ml-10px">请选择</el-button>
              </div>
            </div>
          </el-form-item>
          <!-- 房屋选择 -->
          <el-form-item v-if="form.chargeScope === '1' && typeNamelist.includes(typeName)">
            <div class="residentBox">
              <House returnvalue="houseId" ref="HolderRef" :isMultiple="true" @change="handleSelect"> </House>
            </div>
          </el-form-item>
          <!-- 业主选择 -->
          <el-form-item v-if="form.chargeScope === '1' && !typeNamelist.includes(typeName)">
            <!-- 业主选择 车位费用 -->
            <div class="residentBox" v-if="typeName === HandleTypeId.Resident.Parking">
              <CarUser returnvalue="parkingId" ref="ParkinguserRef" :isMultiple="true" @change="handleCheckPaking"></CarUser>
            </div>
            <div class="residentBox" v-else>
              <UserHolder returnvalue="residentId" ref="userRef" :isMultiple="true" @change="handleCheckUser"></UserHolder>
            </div>
          </el-form-item>
          <el-form-item label="费用周期" prop="chargePeriod">
            <el-select v-model="form.chargePeriod">
              <el-option v-for="(item, index) in com_bill_charge_period" :key="index" :value="item.value" :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起止日期" prop="startDate">
            <el-date-picker
              v-model="StartEndDate"
              unlink-panels
              @update:model-value="handleDate"
              @clear="handleClear"
              :value-format="datepicker[2].format"
              :format="datepicker[2].format"
              :type="datepicker[2].type"
              range-separator="到"
              start-placeholder="开始"
              end-placeholder="结束"
            />
          </el-form-item>
          <!-- <el-form-item label="结束日期" prop="price">
            <el-date-picker
              v-model="StartEndDate"
              @update:model-value="handleDate"
              :value-format="datepicker[2].format"
              :format="datepicker[2].format"
              :type="datepicker[2].type"
              range-separator="到"
              start-placeholder="开始"
              end-placeholder="结束"
            />
          </el-form-item> -->
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :rows="5" v-model.trim="form.remark" placeholder="请输入" />
          </el-form-item>

          <el-form-item style="margin-top: 30px">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

import House from '@/components/Holder/house.vue';
import UserHolder from '@/components/Holder/user.vue';
import CarUser from '@/components/Holder/CarUser.vue';

import PageHeader from '@/components/Pageheader/index.vue';
import { listChargeItem } from '@/api/system/SdbChargeItem';
import { getBill, updateBill, addBill, BillHouse, listBillHouse, queryResidentList_holder } from '@/api/system/SdbBill';
import type { DatePickerType } from 'element-plus';
import { formatDate2 } from '@/utils';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_questionnaire_scope } = toRefs<any>(proxy?.useDict('com_questionnaire_scope'));
const { com_bill_charge_scope_house } = toRefs<any>(proxy?.useDict('com_bill_charge_scope_house'));
const { com_bill_charge_period } = toRefs<any>(proxy?.useDict('com_bill_charge_period'));

type PickerConfig = {
  type: DatePickerType;
  format: string;
};
const datepicker: Record<string, PickerConfig> = {
  '0': { type: 'yearrange', format: 'YYYY' },
  '1': { type: 'monthrange', format: 'YYYY-MM' },
  '2': { type: 'daterange', format: 'YYYY-MM-DD' }
};

const router = useRouter();
const route = useRoute();
const formRef = ref();
const form = ref({
  'id': null,
  'billName': '',
  'chargeItemId': '', // 收费项目
  'chargeScope': '0', // 业主范围
  'chargePeriod': '2', // 费用周期
  houseIds: [], // 部分房屋
  residentIds: [], // 部分业主
  parkingIds: [],
  chargeTypeId: '', // typeid
  'startDate': '', // 开始
  'endDate': '', // 结束
  'remark': ''
});
const rules = ref({
  billName: [{ required: true, message: '请输入 项目名称', trigger: 'blur' }],
  chargeItemId: [{ required: true, message: '请选择 收费项目', trigger: 'blur' }],
  chargePeriod: [{ required: true, message: '请选择 费用周期', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择 起止日期', trigger: 'blur' }],
  endDate: [{ required: true, message: '请选择 起止日期', trigger: 'blur' }]
});
const userid = ref(null);

// 开始结束日期
const StartEndDate = ref([]);
function handleDate(val: string[]) {
  if (val === null || val.length === 0) {
    form.value.startDate = '';
    form.value.endDate = '';
  } else {
    form.value.startDate = val[0] + ' 00:00:00';
    form.value.endDate = val[1] + ' 23:59:59';
  }
}
function handleClear() {
  form.value.startDate = '';
  form.value.endDate = '';
}
// 收费类型
const chargeitemlist = ref([]);

// // 房屋列表
// const houselist = ref([]);
// // 住户列表
// const userlist = ref([]);
async function init() {
  listChargeItem({}).then((res) => {
    chargeitemlist.value = res.rows;

    // const res = await listBillHouse({ pageNum: 1, pageSize: 999999 });
    // houselist.value = res.rows;
    // const res2 = await queryResidentList_holder({ pageNum: 1, pageSize: 999999 });
    // userlist.value = res2.rows;

    if (route.query.id) {
      userid.value = route.query.id;
      getBill(userid.value).then((res) => {
        if (!res.data) return;
        form.value = {
          ...form.value,
          ...res.data
        };
        // TODO 没有住户参数
        form.value.houseIds = res.data.houseIds || [];
        form.value.residentIds = res.data.residentIds || [];
        form.value.parkingIds = res.data.parkingIds || [];
        form.value.startDate = formatDate2(form.value.startDate);
        form.value.endDate = formatDate2(form.value.endDate);
        StartEndDate.value = [form.value.startDate, form.value.endDate];
        // TODO  houseid 有默认值， 需要处理
        // TODO  residentids 添加，
        checkoutHouses.value = [];
        checkoutUser.value = [];
        checkoutParking.value = [];
        checkoutHouses.value = form.value.houseIds.filter((item) => item);
        checkoutUser.value = form.value.residentIds.filter((item) => item);
        checkoutParking.value = form.value.parkingIds.filter((item) => item);
        handleChange(form.value.chargeItemId);
      });
    }
  });
}
init();

const HandleTypeId = {
  /** 显示房屋 */
  'House': {
    /** 水费 */
    'Water': '2049026484272791553',
    /** 电费 */
    'Electricity': '2049026503017136129'
  },
  /** 显示业主 */
  'Resident': {
    /** 车位费 */
    'Parking': '2049026574236418050'
  }
};
// 符合类型： 显示房屋，选择房屋
const typeNamelist = ref([HandleTypeId.House.Water, HandleTypeId.House.Electricity]);
const typeName = ref('');
// 获取收费类型id
function handleChange(val: string, callback: boolean = false) {
  const find = chargeitemlist.value.find((item) => item.id === val);
  if (find) {
    form.value.chargeTypeId = find.typeId;
    typeName.value = find.typeId;
    if (callback) {
      handleClearCheckout();
    }
  }
}
// !== 业主 =============================================================================

// 多选
const checkoutHouses = ref<string[]>([]);
function handleSelect(val: string[]) {
  checkoutHouses.value = val;
  form.value.houseIds = checkoutHouses.value.map((item) => item).filter((item) => item);
}
// 多选
const checkoutUser = ref([]);
/** 添加 业主 */
function handleCheckUser(val: string[]) {
  checkoutUser.value = val;
  form.value.residentIds = val;
}
const checkoutParking = ref([]);
/** 添加 车位业主 */
function handleCheckPaking(val: string[]) {
  checkoutParking.value = val;
  console.log(val);
  form.value.parkingIds = val;
}

/** 清空 */
function handleClearCheckout() {
  checkoutHouses.value = [];
  checkoutUser.value = [];
  form.value.residentIds = [];
  form.value.houseIds = [];
}

// 打开
const HolderRef = ref<InstanceType<typeof House>>();
const userRef = ref<InstanceType<typeof UserHolder>>();
const ParkinguserRef = ref<InstanceType<typeof CarUser>>();
function OpenUseTablesfun(val: string) {
  if (val === 'house') {
    HolderRef.value.open(checkoutHouses.value);
  } else if (val === 'user') {
    if (typeName.value === HandleTypeId.Resident.Parking) {
      ParkinguserRef.value.open(checkoutParking.value);
    } else {
      userRef.value.open(checkoutUser.value);
    }
  }
}
// !== 业主 =============================================================================

// !== 提交 =============================================================================
const submitForm = () => {
  console.log(form.value);
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (userid.value) {
        updateBill(form.value).then(() => {
          ElMessage.success('编辑成功');
          cancelForm();
        });
      } else {
        addBill(form.value).then(() => {
          ElMessage.success('添加成功');
          cancelForm();
        });
      }
    }
  });
};
// 推出
const cancelForm = () => {
  router.back();
};
</script>

<style scoped lang="scss">
.AddBuildingBox {
  padding: 15px;
  height: 100%;
  width: 100%;
}
.AddBuildingBody {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: white;
  padding: 15px;
  .title {
    height: 40px;
    line-height: 40px;
    padding-left: 20px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(16, 16, 16, 1);
    border-bottom: 1px solid #bbbbbb;
    margin-bottom: 60px;
  }

  .formBody {
    width: 950px;
    margin: 0 auto;

    .residentBox {
      max-height: 400px;
      overflow-y: auto;
      padding: 10px 5px;
    }
    .checkoutSideUsesbox {
      // display: grid;
      // grid-template-columns: repeat(3, 1fr);
      // gap: 5px;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      justify-content: space-between;
      padding: 10px 5px;
      li {
        margin-right: 10px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        min-width: 240px;
        height: 35px;
        padding: 0 10px;
        line-height: 35px;

        background-color: #f3f9ff;
        border: 1px solid #8fc0f1;

        margin-bottom: 10px;

        @media (max-width: 2000px) {
          font-size: 12px;
        }
        @media (max-width: 1650px) {
          font-size: 10px;
        }
        @media (max-width: 1650px) {
          font-size: 8px;
        }
        .el-icon {
          margin-left: 20px;
          cursor: pointer;
          &:hover {
            color: red;
          }
        }
        &.add {
          cursor: pointer;
          justify-content: center;
          color: #409eff;
          border: 1px dashed #409eff;
          background-color: transparent;
          &:hover {
            background-color: #40a0ff10;
          }
          span {
            margin-left: 10px;
          }
        }
      }
    }
    &:deep(.el-form-item__content, .el-select, .el-input) {
      width: 350px !important;
      margin-right: 10px;
      .el-cascader {
        width: 100%;
      }
    }
    .el-form-item {
      margin-bottom: 20px;
      align-items: center;
    }
    .el-button {
      width: 80px;
      height: 35px;
      margin-right: 20px;
    }
  }
}
</style>
