<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品状态" prop="productStatus">
        <el-select
          v-model="queryParams.productStatus"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in bx_product_status"
            :key="dict.value"
            :label="dict.label"
            :value="Number(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="insuranceList">
      <el-table-column label="产品类型" prop="productType" width="150" align="left" fixed="left">
        <template #default="scope">
          <dict-tag :options="bx_product_type" :value="scope.row.productType" />
        </template>
      </el-table-column>
      <el-table-column label="产品图片" align="center" prop="picture" width="150">
        <template #default="scope">
          <!--  :preview-src-list="[scope.row.logoUrl]" -->
          <el-image
            v-if="scope.row.picture"
            :src="scope.row.picture"
            class="logo-image"
            fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column
        label="所属租户名称"
        prop="tenantName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="所属项目名称"
        prop="projectName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="产品名称"
        prop="productName"
        :show-overflow-tooltip="true"
        width="150"
        align="left"
      />

      <el-table-column label="产品状态" prop="productStatus" width="150" align="left">
        <template #default="scope">
          <dict-tag :options="bx_product_status" :value="scope.row.productStatus" />
        </template>
      </el-table-column>
      <el-table-column label="作用域" prop="scope" width="150" align="left">
        <template #default="scope">
          <dict-tag :options="sys_scope" :value="scope.row.scope" />
        </template>
      </el-table-column>
      <el-table-column label="货币类型" prop="currency" width="150" align="left">
        <template #default="scope">
          <dict-tag :options="bx_currency_type" :value="scope.row.currency" />
        </template>
      </el-table-column>
      <el-table-column
        label="供款年期(年)"
        width="150"
        align="left"
        prop="paymentTerm"
      ></el-table-column>
      <el-table-column
        label="受保年龄范围(岁)"
        prop="insuredAgeRange"
        :show-overflow-tooltip="true"
        width="150"
        align="left"
      />
      <el-table-column
        label="基础费率(%)"
        prop="premiumRate"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="区分吸烟" prop="smokingAllowed" width="150" align="left">
        <template #default="scope">
          <dict-tag :options="bx_smoking_allowed" :value="scope.row.smokingAllowed" />
        </template>
      </el-table-column>
      <el-table-column
        label="保障内容"
        prop="coverageContent"
        :show-overflow-tooltip="true"
        width="200"
        align="left"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-button
              link
              type="primary"
              icon="Edit"
              style="margin-right: 10px"
              @click="handleUpdate(scope.row)"
              v-if="
                (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
                userStore.isSuperAdmin === 1
              "
              >修改</el-button
            >
            <el-dropdown
              v-if="
                (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
                userStore.isSuperAdmin === 1
              "
              @command="handleStatusCommand"
            >
              <el-button link type="primary" icon="Edit"> 产品状态 </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: '在售', row: scope.row }"
                    >在售</el-dropdown-item
                  >
                  <el-dropdown-item :command="{ action: '下架', row: scope.row }"
                    >下架</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            v-if="
              (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
              userStore.isSuperAdmin === 1
            "
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 作用域选择 -->
            <el-form-item label="作用域" prop="scope">
              <el-select v-model="form.scope" placeholder="请输入" @change="handleScopeChange">
                <el-option
                  v-for="item in filteredScopeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="[2].includes(form.scope) || [3].includes(form.scope)">
            <el-form-item v-if="[2].includes(form.scope)" label="所属租户" prop="tenantBizId">
              <template #label>
                <span>
                  <el-tooltip content="所属租户" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  所属租户
                </span>
              </template>
              <el-select
                v-model="form.tenantBizId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索租户"
                :remote-method="searchTenants"
                :loading="tenantLoading"
              >
                <el-option
                  v-for="item in tenantOptions"
                  :key="item.tenantBizId"
                  :label="item.tenantName"
                  :value="item.tenantBizId"
                />
              </el-select>
            </el-form-item>

            <el-form-item v-if="[3].includes(form.scope)" label="所属项目" prop="projectBizId">
              <template #label>
                <span>
                  <el-tooltip content="所属项目" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  所属项目
                </span>
              </template>
              <el-select
                v-model="form.projectBizId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索项目"
                :remote-method="searchProjects"
                :loading="projectLoading"
              >
                <el-option
                  v-for="item in projectOptions"
                  :key="item.projectBizId"
                  :label="item.projectName"
                  :value="item.projectBizId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-select v-model="form.productType" placeholder="请选择">
                <el-option
                  v-for="item in bx_product_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货币" prop="currency">
              <el-select v-model="form.currency" placeholder="请选择">
                <el-option
                  v-for="item in bx_currency_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="基础费率" prop="premiumRate">
              <div class="years">
                <el-input
                  placeholder="请输入"
                  v-model="form.premiumRate"
                  type="number"
                  min="0"
                  max="100"
                  @input="handlePremiumRateInput"
                />
                <div class="hao">%</div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否区分吸烟" prop="smokingAllowed">
              <el-select v-model="form.smokingAllowed" placeholder="请选择">
                <el-option
                  v-for="item in bx_smoking_allowed"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品状态" prop="productStatus">
              <el-select v-model="form.productStatus" placeholder="请选择">
                <el-option
                  v-for="item in bx_product_status"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="timeRange">
              <el-form-item label="受保年龄范围" prop="startAge" style="width: 120%">
                <el-input
                  placeholder="起保年龄"
                  v-model="form.startAge"
                  type="number"
                  min="0"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                />
              </el-form-item>
              <div class="line">-</div>
              <el-form-item label="" prop="endAge">
                <el-input
                  placeholder="终保年龄"
                  v-model="form.endAge"
                  type="number"
                  min="0"
                  oninput="value=value.replace(/[^0-9]/g,'')"
                />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属保险公司" prop="ssDeptBizIdList">
              <el-tooltip
                :disabled="!showSsDeptTooltip"
                placement="top"
                :content="ssDeptSelectedLabels"
              >
                <el-select
                  v-model="form.ssDeptBizIdList"
                  multiple
                  collapse-tags
                  :collapse-tags-tooltip="false"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索公司"
                  :remote-method="searchCompanys"
                  :loading="companyLoading"
                  @mouseenter.native="handleSelectMouseEnter('ssDept')"
                  @mouseleave.native="handleSelectMouseLeave('ssDept')"
                >
                  <el-option
                    v-for="item in companyOptions"
                    :key="item.deptBizId"
                    :label="item.deptName"
                    :value="item.deptBizId"
                  />
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出单公司" prop="cdDeptBizIdList">
              <el-tooltip
                :disabled="!showCdDeptTooltip"
                placement="top"
                :content="cdDeptSelectedLabels"
              >
                <el-select
                  v-model="form.cdDeptBizIdList"
                  multiple
                  collapse-tags
                  :collapse-tags-tooltip="false"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索公司"
                  :remote-method="searchCompanys"
                  :loading="companyLoading"
                  @mouseenter.native="handleSelectMouseEnter('cdDept')"
                  @mouseleave.native="handleSelectMouseLeave('cdDept')"
                >
                  <el-option
                    v-for="item in companyOptions"
                    :key="item.deptBizId"
                    :label="item.deptName"
                    :value="item.deptBizId"
                  />
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品计划" prop="planBizIdList">
              <el-tooltip
                :disabled="!showPlanTooltip"
                placement="top"
                :content="planSelectedLabels"
              >
                <el-select
                  v-model="form.planBizIdList"
                  multiple
                  collapse-tags
                  :collapse-tags-tooltip="false"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索计划产品"
                  :remote-method="searchPlanProduct"
                  :loading="planLoading"
                  @mouseenter.native="handleSelectMouseEnter('plan')"
                  @mouseleave.native="handleSelectMouseLeave('plan')"
                >
                  <el-option
                    v-for="item in planOptions"
                    :key="item.planBizId"
                    :label="item.planName"
                    :value="item.planBizId"
                  />
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附加产品" prop="additionalProductBizIdList">
              <el-tooltip
                :disabled="!showAdditionalTooltip"
                placement="top"
                :content="additionalSelectedLabels"
              >
                <el-select
                  v-model="form.additionalProductBizIdList"
                  multiple
                  collapse-tags
                  :collapse-tags-tooltip="false"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词搜索附加产品"
                  :remote-method="searchAdditionalProduct"
                  :loading="additionalLoading"
                  @mouseenter.native="handleSelectMouseEnter('additional')"
                  @mouseleave.native="handleSelectMouseLeave('additional')"
                >
                  <el-option
                    v-for="item in additionalOptions"
                    :key="item.additionalProductBizId"
                    :label="item.productName"
                    :value="item.additionalProductBizId"
                  />
                </el-select>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属公司所在地" prop="location">
              <el-input
                v-model="form.location"
                type="text"
                placeholder="请输入公司所在地"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保障内容" prop="coverageContent">
              <el-input
                v-model="form.coverageContent"
                type="textarea"
                placeholder="请输入保障内容"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="产品图片"
              prop="picture"
              :rules="[{ required: true, message: '请上传产品图片', trigger: 'change' }]"
            >
              <image-upload
                v-model="form.picture"
                :action="'/oss/api/oss/upload'"
                :limit="1"
                :file-size="5"
                :file-type="['png', 'jpg', 'jpeg']"
                :is-show-tip="true"
                @change="handleImageChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" v-for="(item, index) in form.tempTermList" :key="item.id">
            <el-form-item
              :label="`供款年期${index + 1}`"
              :prop="`tempTermList.${index}.paymentTerm`"
              :rules="[{ required: true, message: '供款年期不能为空', trigger: 'blur' }]"
            >
              <div class="termBox">
                <el-input
                  v-model="item.paymentTerm"
                  placeholder="请输入年期"
                  style="margin-right: 10px"
                ></el-input>
                <el-button
                  circle
                  icon="plus"
                  @click="addPaymentTerm"
                  v-if="index === form.tempTermList.length - 1"
                />
                <el-button circle icon="delete" @click="removePaymentTerm(index)" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="InsuranceProduct">
import { delRole, searchScopeList } from '@/api/system/role'
import {
  getInsuranceProductList,
  editProductStatus,
  addInsuranceProduct,
  getInsuranceProducPlanList,
  editInsuranceProduct,
  getProductDetail,
  getAdditionalProductList
} from '@/api/insurance/index'
import { getAllCompanys } from '@/api/system/dept'
import useUserStore from '@/store/modules/user'
import { computed, ref } from 'vue'
import ImageUpload from '@/components/ImageUpload/index.vue' //图片上传组件

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { bx_product_type, sys_scope, bx_product_status, bx_smoking_allowed, bx_currency_type } =
  proxy.useDict(
    'bx_product_type',
    'sys_scope',
    'bx_product_status',
    'bx_smoking_allowed',
    'bx_currency_type'
  )
const insuranceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const companyLoading = ref(false)
const companyOptions = ref([])
const planLoading = ref(false)
const additionalLoading = ref(false)
const planOptions = ref([])
const additionalOptions = ref([])
//在data中添加一个用于跟踪图片上传状态的变量
const imageUploaded = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    productName: undefined,
    productStatus: undefined
  },
  rules: {
    productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
    scope: [{ required: true, message: '作用域不能为空', trigger: 'blur' }],
    productType: [{ required: true, message: '产品类型不能为空', trigger: 'blur' }],
    currency: [{ required: true, message: '货币不能为空', trigger: 'blur' }],
    premiumRate: [
      { required: true, message: '基础费率不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value === '' || value === null) {
            callback(new Error('基础费率不能为空'))
            return
          }

          const numValue = Number(value)
          if (isNaN(numValue)) {
            callback(new Error('请输入有效的数字'))
          } else if (numValue < 0) {
            callback(new Error('基础费率不能小于0'))
          } else if (numValue > 100) {
            callback(new Error('基础费率不能大于100'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    smokingAllowed: [{ required: true, message: '是否区分吸烟不能为空', trigger: 'blur' }],
    productStatus: [{ required: true, message: '产品状态不能为空', trigger: 'blur' }],
    startAge: [
      { required: true, message: '起保年龄不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!Number.isInteger(Number(value)) || value <= 0) {
            callback(new Error('请输入正整数'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    endAge: [
      { required: true, message: '终保年龄不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (!Number.isInteger(Number(value)) || value <= 0) {
            callback(new Error('请输入正整数'))
          } else if (Number(value) <= Number(form.value.startAge)) {
            callback(new Error('终保必须大于起保'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    tenantBizId: [{ required: true, message: '所属租户不能为空', trigger: 'blur' }],
    ssDeptBizIdList: [
      {
        required: true,
        message: '所属保险公司不能为空',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (!value || value.length === 0) {
            callback(new Error('请至少选择一个所属保险公司'))
          } else {
            callback()
          }
        }
      }
    ],
    picture: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!value || value.trim() === '') {
            callback(new Error('请上传产品图片'))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)
const filteredScopeOptions = computed(() => {
  if (!sys_scope.value || !Array.isArray(sys_scope.value)) return []

  return sys_scope.value.filter(option => {
    // 添加安全判断
    if (!option || typeof option.value === 'undefined') return false
    return Number(option.value) !== 3
  })
})
// 添加图片变更处理函数
function handleImageChange(value) {
  imageUploaded.value = !!value
  // 手动触发表单验证
  if (proxy.$refs.form) {
    proxy.$refs.form.validateField('picture')
  }
}
const handlePremiumRateInput = value => {
  // 限制输入范围为0-100
  if (value > 100) {
    form.value.premiumRate = 100
  } else if (value < 0) {
    form.value.premiumRate = 0
  }

  // 限制小数位数为2位
  if (value && value.toString().includes('.')) {
    const parts = value.toString().split('.')
    if (parts[1].length > 2) {
      form.value.premiumRate = Number(value).toFixed(2)
    }
  }
}
const handleStatusCommand = command => {
  const { row, action } = command
  const newStatus = row.productStatus === 1 ? 0 : 1 // 获取切换后的新状态
  proxy.$modal
    .confirm(`确认要${action}"${row.productName}"吗?`)
    .then(function () {
      return editProductStatus(row.productBizId, newStatus).then(() => {
        proxy.$modal.msgSuccess(`${row.productName}${action}成功`)
        getList()
      })
    })
    .catch(() => {})
}
/** 查询角色列表 */
function getList() {
  loading.value = true
  getInsuranceProductList(queryParams.value).then(response => {
    if (response.code === 200) {
      insuranceList.value = response.data.records
      total.value = response.data.total
      loading.value = false
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.roleId || ids.value
  proxy.$modal
    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
    .then(function () {
      return delRole(roleIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    tempTermList: [],
    ssDeptBizIdList: [],
    cdDeptBizIdList: [],
    planBizIdList: [],
    additionalProductBizIdList: []
  }
  proxy.resetForm('roleRef')
}

/** 添加角色 */
function handleAdd() {
  form.value = {
    tempTermList: [],
    ssDeptBizIdList: [],
    cdDeptBizIdList: [],
    planBizIdList: [],
    additionalProductBizIdList: []
  }
  form.value.tempTermList.push({ id: 1 })

  searchCompanys('') //搜索公司
  searchPlanProduct('') //搜索计划产品
  searchAdditionalProduct('') //搜索附加产品
  open.value = true
  title.value = '添加产品'
}

/** 修改产品 */
function handleUpdate(row) {
  reset()
  searchCompanys('') //搜索公司
  searchPlanProduct('') //搜索计划产品
  searchAdditionalProduct('') //搜索附加产品

  const productBizId = row.productBizId
  getProductDetail(productBizId).then(response => {
    if (response.code === 200) {
      console.log('response.data', response.data)
      let result = response.data
      form.value.tempTermList = result.paymentTermList.map((item, index) => {
        return {
          id: index + 1,
          paymentTerm: item
        }
      })
      // 回显保险公司数据
      form.value.ssDeptBizIdList = result.ssDeptDtoList.map(item => item.deptBizId)
      // 回显出单公司数据
      form.value.cdDeptBizIdList = result.cdDeptDtoList.map(item => item.deptBizId)
      // 回显产品计划数据
      form.value.planBizIdList = result.planDtoList.map(item => item.planBizId)
      // 回显附加产品数据
      form.value.additionalProductBizIdList = result.insuranceAdditionalProductDtoList.map(
        item => item.additionalProductBizId
      )
      form.value.startAge = result.insuredAgeRange.split('-')[0]
      form.value.endAge = result.insuredAgeRange.split('-')[1]
      form.value = Object.assign({}, form.value, result)
      // 根据作用域类型预加载关联数据
      if (response.data.scope === 2) {
        tenantOptions.value.push({
          tenantBizId: response.data.tenantBizId,
          tenantName: response.data.tenantName
        })
      } else if (response.data.scope === 3) {
        projectOptions.value.push({
          projectBizId: response.data.projectBizId,
          projectName: response.data.projectName
        })
      }

      open.value = true
      title.value = '修改产品'
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['roleRef'].validate(valid => {
    if (valid) {
      let newTermList = JSON.parse(JSON.stringify(form.value.tempTermList))
      form.value.paymentTermList = newTermList.map(item => item.paymentTerm)
      form.value.insuredAgeRange = `${form.value.startAge}-${form.value.endAge}`
      if (form.value.productBizId) {
        editInsuranceProduct(form.value).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      } else {
        addInsuranceProduct(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}
getList()

//========作用域-切换逻辑开始=========
const tenantOptions = ref([])
const tenantLoading = ref(false)
const projectOptions = ref([])
const projectLoading = ref(false)
// 作用域变更处理
function handleScopeChange(val) {
  console.log('作用域变更:', val)

  // 清空不需要的字段值
  if (val === 2) {
    form.value.projectBizId = ''
    // 自动加载租户列表（可选）
    searchTenants('')
  } else if (val === 3) {
    form.value.tenantBizId = ''
    // 自动加载项目列表（可选）
    searchProjects('')
  } else if (val === 1) {
    //系统级
    form.value.tenantBizId = ''
    form.value.projectBizId = ''
  }
}

// 搜索租户方法
function searchTenants(query) {
  tenantLoading.value = true
  try {
    const params = {
      loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
      scope: 2,
      name: query,
      pageNo: 1,
      pageSize: 10
    }

    searchScopeList(params).then(response => {
      tenantOptions.value = response.data.records
    })
  } catch (error) {
    console.error('租户搜索失败', error)
    tenantOptions.value = []
  } finally {
    tenantLoading.value = false
  }
}

// 搜索项目方法
function searchProjects(query) {
  projectLoading.value = true
  try {
    const params = {
      loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
      scope: 3,
      name: query,
      pageNo: 1,
      pageSize: 10
    }
    searchScopeList(params).then(response => {
      projectOptions.value = response.data.records
    })
  } catch (error) {
    console.error('项目搜索失败', error)
    projectOptions.value = []
  } finally {
    projectLoading.value = false
  }
}
//========作用域-切换逻辑结束=========
// 新增供款年期
const addPaymentTerm = () => {
  form.value.tempTermList.push({
    id: form.value.tempTermList.length + 1
  })
}
// 删除供款年期
const removePaymentTerm = index => {
  if (form.value.tempTermList.length == 1) {
    proxy.$modal.msgError('供款年期不能为空')
    return
  }
  form.value.tempTermList.splice(index, 1)
}
// 搜索公司方法
const searchCompanys = query => {
  companyLoading.value = true
  try {
    const params = {
      deptName: query,
      pageNo: 1,
      pageSize: 10
    }

    getAllCompanys(params).then(response => {
      companyOptions.value = response.data.records
    })
  } catch (error) {
    console.error('公司搜索失败', error)
    companyOptions.value = []
  } finally {
    companyLoading.value = false
  }
}
// 搜索计划产品
const searchPlanProduct = query => {
  planLoading.value = true
  try {
    const params = {
      planName: query,
      pageNo: 1,
      pageSize: 10
    }

    getInsuranceProducPlanList(params).then(response => {
      planOptions.value = response.data.records
    })
  } catch (error) {
    console.error('公司搜索失败', error)
    planOptions.value = []
  } finally {
    planLoading.value = false
  }
}
// 搜索附加产品
const searchAdditionalProduct = query => {
  additionalLoading.value = true
  try {
    const params = {
      productName: query,
      pageNo: 1,
      pageSize: 10
    }

    getAdditionalProductList(params).then(response => {
      additionalOptions.value = response.data.records
    })
  } catch (error) {
    console.error('附加产品搜索失败', error)
    additionalOptions.value = []
  } finally {
    additionalLoading.value = false
  }
}
//========多选下拉框悬停效果开始=========
// 新增响应式数据
const showSsDeptTooltip = ref(false)
const showCdDeptTooltip = ref(false)
const showPlanTooltip = ref(false)
const showAdditionalTooltip = ref(false)

// 计算选中项的标签文本
const ssDeptSelectedLabels = computed(() => {
  return form.value.ssDeptBizIdList
    .map(id => {
      const item = companyOptions.value.find(opt => opt.deptBizId === id)
      return item ? item.deptName : id
    })
    .join('、')
})

const cdDeptSelectedLabels = computed(() => {
  return form.value.cdDeptBizIdList
    .map(id => {
      const item = companyOptions.value.find(opt => opt.deptBizId === id)
      return item ? item.deptName : id
    })
    .join('、')
})

const planSelectedLabels = computed(() => {
  return form.value.planBizIdList
    .map(id => {
      const item = planOptions.value.find(opt => opt.planBizId === id)
      return item ? item.planName : id
    })
    .join('、')
})
const additionalSelectedLabels = computed(() => {
  return form.value.additionalProductBizIdList
    .map(id => {
      const item = additionalOptions.value.find(opt => opt.additionalProductBizId === id)
      return item ? item.productName : id
    })
    .join('、')
})

// 处理鼠标进入select
const handleSelectMouseEnter = type => {
  // 判断是否有折叠的标签（选中数量超过显示数量）
  let hasCollapsedTags = false
  switch (type) {
    case 'ssDept':
      hasCollapsedTags = form.value.ssDeptBizIdList.length > 0
      break
    case 'cdDept':
      hasCollapsedTags = form.value.cdDeptBizIdList.length > 0
      break
    case 'plan':
      hasCollapsedTags = form.value.planBizIdList.length > 0
      break
    case 'additional':
      hasCollapsedTags = form.value.additionalProductBizIdList.length > 0
      break
  }

  if (hasCollapsedTags) {
    switch (type) {
      case 'ssDept':
        showSsDeptTooltip.value = true
        break
      case 'cdDept':
        showCdDeptTooltip.value = true
        break
      case 'plan':
        showPlanTooltip.value = true
        break
      case 'additional':
        showAdditionalTooltip.value = true
        break
    }
  }
}

// 处理鼠标离开select
const handleSelectMouseLeave = type => {
  switch (type) {
    case 'ssDept':
      showSsDeptTooltip.value = false
      break
    case 'cdDept':
      showCdDeptTooltip.value = false
      break
    case 'plan':
      showPlanTooltip.value = false
      break
    case 'additional':
      showAdditionalTooltip.value = false
      break
  }
}
//========多选下拉框悬停效果结束=========
</script>
<style lang="scss" scoped>
.logo-image {
  width: 70px;
  height: 70px;
  border-radius: 4px;
  object-fit: cover;
}
.years {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  .line {
    margin: 0 10px;
  }
}
.termBox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
.timeRange {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  .line {
    margin: 0 10px;
  }
}
.timeRange ::v-deep .el-form-item--default .el-form-item__content {
  margin-left: 0 !important;
}
</style>
