<template>
  <div class="institution-form">
    <el-form ref="dataFormRef" :model="formData" :rules="rules" label-suffix=":" label-width="160px"
      label-position="right">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="制度名称" prop="name">
            <el-input v-model="formData.name" placeholder="最多50字" :maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用类型" prop="expense_type">
            <el-select v-model="formData.expense_type" placeholder="请选择费用类型" style="width: 100%">
              <el-option
                v-for="opt in EXPENSE_TYPE_OPTIONS"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="制度生效时间" prop="effective_start_date">
            <el-date-picker v-model="formData.effective_start_date" type="date" placeholder="开始时间" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="制度失效时间" prop="effective_end_date">
            <div class="date-picker-wrapper">
              <el-date-picker v-model="formData.effective_end_date" type="date"
                :placeholder="formData.is_long_term ? '长期有效' : '请选择日期'" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                :disabled="formData.is_long_term" />
              <el-checkbox v-model="formData.is_long_term" label="长期有效" class="long-term-checkbox" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="额度发放" prop="grant_mode">
            <el-radio-group v-model="formData.grant_mode">
              <el-radio value="period">按固定周期发放</el-radio>
              <el-radio value="manual">按手工发放</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="formData.grant_mode === 'period'" :gutter="20" class="period-config">
        <el-col :span="24">
          <el-form-item label="" prop="period_type">
            <el-radio-group v-model="formData.period_type">
              <el-radio value="daily">每日额度</el-radio>
              <el-radio value="monthly">每月额度</el-radio>
              <el-radio value="weekly">每周额度</el-radio>
              <el-radio value="quarterly">每季额度</el-radio>
              <el-radio value="yearly">每年额度</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="" prop="amount">
            <el-input-number v-model="formData.amount" controls-position="right" placeholder="输入金额" :min="0"
              :precision="2">
              <template #suffix>
                <span>元</span>
              </template>
            </el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="period-config__collapse">
          <el-button type="text" @click="togglePeriodCollapse">
            {{ isPeriodCollapsed ? "更多设置" : "收起" }}
          </el-button>
        </el-col>

        <div v-show="!isPeriodCollapsed">
          <el-col :span="24">
            <el-form-item label="有效时间" prop="effective_time_type">
              <el-radio-group v-model="formData.effective_time_type">
                <el-radio value="unlimited">不限制</el-radio>
                <el-radio value="workday">工作日/节假日</el-radio>
                <!-- <el-radio value="custom">自定义限制</el-radio> -->
              </el-radio-group>
            </el-form-item>
          </el-col>

          <template v-if="formData.effective_time_type === 'workday'">
            <el-col :span="24">
              <el-form-item>
                <div class="workday-config">
                  <div class="workday-config__item">
                    <span class="workday-config__label">工作日</span>
                    <el-time-picker v-model="formData.workday_start_time" type="time" placeholder="请选择时间" format="HH:mm"
                      value-format="HH:mm" />
                    <span class="workday-config__separator">-</span>
                    <el-select v-model="formData.workday_end_type" placeholder="选择" style="width: 80px;">
                      <el-option label="当日" value="same_day" />
                      <el-option label="次日" value="next_day" />
                    </el-select>
                    <el-time-picker v-model="formData.workday_end_time" type="time" placeholder="请选择时间" format="HH:mm"
                      value-format="HH:mm" />
                  </div>

                  <div class="workday-config__item">
                    <span class="workday-config__label">节假日</span>
                    <el-time-picker v-model="formData.holiday_start_time" type="time" placeholder="请选择时间" format="HH:mm"
                      value-format="HH:mm" />
                    <span class="workday-config__separator">-</span>
                    <el-select v-model="formData.holiday_end_type" placeholder="选择" style="width: 80px;">
                      <el-option label="当日" value="same_day" />
                      <el-option label="次日" value="next_day" />
                    </el-select>
                    <el-time-picker v-model="formData.holiday_end_time" type="time" placeholder="请选择时间" format="HH:mm"
                      value-format="HH:mm" />
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="24">
            <el-form-item label="单次限额" prop="single_limit">
              <el-input-number v-model="formData.single_limit" controls-position="right" placeholder="输入金额" :min="0"
                :precision="2">
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </div>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="适用员工" prop="applicable_scope">
                <el-radio-group v-model="formData.applicable_scope">
                  <el-radio value="department">按部门</el-radio>
                  <el-radio value="employee">按员工</el-radio>
                  <el-radio value="all">全体员工</el-radio>
                  <!-- <el-radio value="tag">按员工标签</el-radio> -->
                  <el-radio value="none">暂不设置</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col v-if="formData.applicable_scope === 'department'" :span="12">
              <el-form-item label="选择部门" prop="department_id">
                <el-select v-model="formData.department_id" placeholder="选择部门" style="width: 100%">
                  <el-option v-for="dept in departmentOptions" :key="dept.value" :label="dept.label"
                    :value="dept.value" />
                </el-select>
                <div class="department-tip">
                  按部门选择后，制度将在所选部门内所有员工生效，若部门中变更员工，将直接适用这条制度，需谨慎选择
                </div>
              </el-form-item>
            </el-col>

            <el-col v-if="formData.applicable_scope === 'employee'" :span="12">
              <el-form-item v-if="formData.applicable_scope === 'employee'" label="选择员工" prop="employee_ids">
                <div>
                  <el-button type="primary" plain @click="showEmployeeSelector = true">
                    选择员工
                  </el-button>
                  <div v-if="selectedEmployeeNames.length > 0" class="selected-employees">
                    已选: {{ selectedEmployeeNames.join(", ") }}
                  </div>
                  <div v-else class="selected-employees warning">
                    请完成适用员工选择
                  </div>
                </div>
              </el-form-item>
            </el-col>

            <el-col v-if="formData.applicable_scope === 'tag'" :span="12">
              <el-form-item label="选择标签" prop="tag_ids">
                <el-select v-model="formData.tag_ids" placeholder="选择员工标签" multiple style="width: 100%">
                  <el-option v-for="tag in tagOptions" :key="tag.value" :label="tag.label" :value="tag.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="是否启用" prop="effective">
            <el-radio-group v-model="formData.effective">
              <el-radio value="1">启用</el-radio>
              <el-radio value="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="费控咨询模式" prop="consult_mode">
            <el-radio-group v-model="formData.consult_mode">
              <el-radio value="0">支付宝内部计算</el-radio>
              <el-radio value="1">咨询外部服务商</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
        </el-col>
      </el-row>
    </el-form>

    <EmployeeSelector v-model:visible="showEmployeeSelector" :selected-ids="formData.employee_ids"
      :enterprise-id="formData.enterprise_id" @confirm="handleEmployeeConfirm" />
  </div>
</template>

<script setup lang="ts">
import {
  EXPENSE_TYPE_OPTIONS,
  CONSULT_MODE_OPTIONS,
  InstitutionForm,
  InstitutionDetail,
} from "@/api/module_payment/institution";
import InstitutionAPI from "@/api/module_payment/institution";
import { reactive, ref, watch, computed } from "vue";
import EmployeeSelector from "./EmployeeSelector.vue";

interface Props {
  type: "create" | "update";
  institutionId?: string;
  enterpriseId?: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: "success"): void;
}>();

const dataFormRef = ref();

const initialFormData = {
  enterprise_id: undefined as string | undefined,
  name: undefined,
  expense_type: "GENERAL",
  effective: "1",
  institution_desc: undefined,
  effective_start_date: undefined,
  effective_end_date: undefined,
  consult_mode: "0",
  grant_mode: "period",
  applicable_scope: "none",
  is_long_term: false,
  period_type: "monthly",
  amount: undefined,
  effective_time_type: "unlimited",
  single_limit: undefined,
  workday_start_time: undefined,
  workday_end_type: "same_day",
  workday_end_time: undefined,
  holiday_start_time: undefined,
  holiday_end_type: "same_day",
  holiday_end_time: undefined,
  department_id: undefined,
  employee_ids: [] as string[],
  tag_ids: [] as string[],
};

const formData = reactive<InstitutionForm & typeof initialFormData>(
  JSON.parse(JSON.stringify(initialFormData))
);

const expandMore = ref<string[]>([]);
const isPeriodCollapsed = ref(false);

function togglePeriodCollapse() {
  isPeriodCollapsed.value = !isPeriodCollapsed.value;
}

const departmentOptions = ref([
  { value: "dept1", label: "研发部" },
  { value: "dept2", label: "产品部" },
  { value: "dept3", label: "运营部" },
  { value: "dept4", label: "财务部" },
]);

const employeeOptions = ref([
  { value: "emp1", label: "张三" },
  { value: "emp2", label: "李四" },
  { value: "emp3", label: "王五" },
  { value: "emp4", label: "赵六" },
]);

const tagOptions = ref([
  { value: "tag1", label: "管理层" },
  { value: "tag2", label: "技术骨干" },
  { value: "tag3", label: "新员工" },
]);

const showEmployeeSelector = ref(false);

const selectedEmployeeNames = computed(() => {
  return formData.employee_ids.map(id => {
    const emp = employeeOptions.value.find(e => e.value === id);
    return emp ? emp.label : id;
  });
});

function handleEmployeeConfirm(ids: string[]) {
  formData.employee_ids = ids;
}

watch(
  () => props.institutionId,
  async (newVal) => {
    if (newVal && props.type === "update") {
      const res = await InstitutionAPI.detailInstitution(newVal, props.enterpriseId);
      const data = res.data.data as InstitutionDetail;
      if (data) {
        formData.enterprise_id = data.enterprise_id;
        formData.name = data.name || data.institution_name;
        formData.expense_type = data.expense_type || "GENERAL";
        formData.effective = data.effective || "1";
        formData.institution_desc = data.institution_desc;
        formData.effective_start_date = data.effective_start_date;
        formData.effective_end_date = data.effective_end_date;
        formData.consult_mode = data.consult_mode || "0";
        formData.grant_mode = data.grant_mode || "period";
        formData.applicable_scope = data.applicable_scope || "none";
        formData.period_type = data.period_type || "monthly";
        formData.amount = data.amount;
        formData.single_limit = data.single_limit;
        formData.effective_time_type = data.effective_time_type || "unlimited";
        formData.employee_ids = data.employee_ids || [];
      }
    }
  },
  { immediate: true }
);

watch(
  () => props.enterpriseId,
  (newVal) => {
    if (newVal && props.type === "create") {
      formData.enterprise_id = newVal;
    }
  },
  { immediate: true }
);

const rules = reactive({
  enterprise_id: [{ required: true, message: "请输入企业ID", trigger: "blur" }],
  name: [{ required: true, message: "请输入制度名称", trigger: "blur" }],
  expense_type: [{ required: true, message: "请选择费用类型", trigger: "change" }],
  effective_start_date: [{ required: true, message: "请选择制度生效时间", trigger: "change" }],
  effective_end_date: [{
    required: true,
    message: "请选择制度失效时间",
    trigger: "change",
    validator: (rule: any, value: any, callback: any) => {
      if (formData.is_long_term) {
        callback();
      } else if (!value) {
        callback(new Error("请选择制度失效时间"));
      } else {
        callback();
      }
    }
  }],
  grant_mode: [{ required: true, message: "请选择额度发放方式", trigger: "change" }],
  period_type: [{
    required: true,
    message: "请选择周期类型",
    trigger: "change",
    validator: (rule: any, value: any, callback: any) => {
      if (formData.grant_mode !== "period") {
        callback();
      } else if (!value) {
        callback(new Error("请选择周期类型"));
      } else {
        callback();
      }
    }
  }],
  amount: [{
    required: true,
    message: "请输入额度金额",
    trigger: "blur",
    validator: (rule: any, value: any, callback: any) => {
      if (formData.grant_mode !== "period") {
        callback();
      } else if (!value || value <= 0) {
        callback(new Error("请输入有效的额度金额"));
      } else {
        callback();
      }
    }
  }],
  applicable_scope: [{ required: true, message: "请选择适用员工范围", trigger: "change" }],
});

async function submitForm() {
  const valid = await dataFormRef.value?.validate().catch(() => false);
  if (!valid) return;

  try {
    // 构建通用表单数据
    const submitData: Record<string, unknown> = {
      enterprise_id: formData.enterprise_id,
      name: formData.name,
      expense_type: formData.expense_type,
      effective: formData.effective,
      institution_desc: formData.institution_desc || undefined,
      effective_start_date: formData.effective_start_date || undefined,
      effective_end_date: formData.is_long_term ? undefined : (formData.effective_end_date || undefined),
      consult_mode: formData.consult_mode || undefined,
      grant_mode: formData.grant_mode,
      applicable_scope: formData.applicable_scope,
    };

    // 适用范围参数
    if (formData.applicable_scope === "department") {
      submitData.scope_owner_type = "ENTERPRISE_PAY_UID";
      submitData.scope_owner_id_list = formData.department_id ? [formData.department_id] : undefined;
    } else if (formData.applicable_scope === "employee") {
      submitData.scope_owner_type = "ENTERPRISE_PAY_UID";
      submitData.scope_owner_id_list = formData.employee_ids;
    }

    // 固定周期发放参数
    if (formData.grant_mode === "period") {
      submitData.period_type = formData.period_type;
      submitData.amount = formData.amount;
      submitData.effective_time_type = formData.effective_time_type;
      submitData.single_limit = formData.single_limit || undefined;

      if (formData.effective_time_type === "workday") {
        submitData.workday_start_time = formData.workday_start_time;
        submitData.workday_end_type = formData.workday_end_type;
        submitData.workday_end_time = formData.workday_end_time;
        submitData.holiday_start_time = formData.holiday_start_time;
        submitData.holiday_end_type = formData.holiday_end_type;
        submitData.holiday_end_time = formData.holiday_end_time;
      }
    }

    if (props.type === "create") {
      await InstitutionAPI.createInstitution(submitData);
    } else if (props.type === "update" && props.institutionId) {
      // 编辑时重命名字段以匹配支付宝 AlipayEbppInvoiceInstitutionModifyModel
      const modifyData: Record<string, unknown> = {
        institution_id: props.institutionId,
        enterprise_id: formData.enterprise_id,
        institution_name: formData.name,
        institution_desc: formData.institution_desc || undefined,
        effective: formData.effective,
        effective_start_date: formData.effective_start_date || undefined,
        effective_end_date: formData.is_long_term ? undefined : (formData.effective_end_date || undefined),
        consult_mode: formData.consult_mode || undefined,
        // 适用员工范围
        applicable_scope: formData.applicable_scope,
        scope_owner_type: "ENTERPRISE_PAY_UID",
        scope_owner_id_list: formData.applicable_scope === "employee"
          ? (formData.employee_ids || [])
          : formData.applicable_scope === "department" && formData.department_id
            ? [formData.department_id]
            : undefined,
        // 额度发放与周期参数
        grant_mode: formData.grant_mode,
        period_type: formData.period_type || "monthly",
        amount: formData.amount,
        single_limit: formData.single_limit,
        effective_time_type: formData.effective_time_type || "unlimited",
        expense_type: formData.expense_type,
      };
      await InstitutionAPI.updateInstitution(props.institutionId, modifyData);
    }
    emit("success");
  } catch (error) {
    console.error(error);
  }
}

function resetForm() {
  Object.assign(formData, JSON.parse(JSON.stringify(initialFormData)));
  dataFormRef.value?.resetFields();
}

defineExpose({
  submitForm,
  resetForm,
});
</script>

<style scoped>
.date-picker-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.long-term-checkbox {
  flex: 1;
}

.el-collapse-item__header {
  padding-left: 0 !important;
  color: #409eff;
}

.el-collapse-item__header:hover {
  color: #66b1ff;
}

.period-config {
  padding: 16px;
  background: #fafafa;
  margin-bottom: 16px;
  border-radius: 4px;
}

.period-config__collapse {
  text-align: left;
  padding-top: 8px;
}

.workday-config {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-top: 8px;
}

.workday-config__item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.workday-config__item:last-child {
  margin-bottom: 0;
}

.workday-config__label {
  width: 60px;
  font-weight: 500;
}

.workday-config__separator {
  color: #999;
}

.department-tip {
  margin-top: 8px;
  padding: 8px 12px;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 4px;
  font-size: 12px;
  color: #d48806;
  line-height: 1.5;
}

.selected-employees {
  margin-top: 8px;
  padding: 6px 12px;
  background: #f0f5ff;
  border: 1px solid #b3d1ff;
  border-radius: 4px;
  font-size: 12px;
  color: #1e88e5;
}

.selected-employees.warning {
  background: #fff2f0;
  border-color: #ffccc7;
  color: #ff4d4f;
}
</style>