<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="产品计划名称" prop="productName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入产品计划名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </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="insurancePlanList">
      <el-table-column label="产品计划名称" prop="planName" :show-overflow-tooltip="true" />
      <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="状态" align="center">
        <template #default="scope">
          <el-switch
            v-if="
              (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
              userStore.isSuperAdmin === 1
            "
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @click="
              evt => {
                evt.preventDefault()
                handleStatusChange(scope.row)
              }
            "
          ></el-switch>
          <dict-tag
            :options="sys_status"
            :value="scope.row.status"
            v-if="userStore.isSuperAdmin === 0 && scope.row.scope === 1"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-if="
              (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
              userStore.isSuperAdmin === 1
            "
            >修改</el-button
          >
          <!-- <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="24">
            <el-form-item label="产品计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入产品计划名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_status"
                  :key="dict.value"
                  :value="Number(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </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-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="InsuranceProductPlan">
import {
  addRole,
  roleStatusChange,
  delRole,
  listRole,
  getRoleDetail,
  roleUpdate,
  searchScopeList
} from '@/api/system/role'
import {
  getInsuranceProducPlanList,
  editPlanStatus,
  addInsuranceProducPlan,
  getInsuranceProducPlanDetail,
  editInsuranceProducPlan
} from '@/api/insurance/index'
import useUserStore from '@/store/modules/user'
import ImageUpload from '@/components/ImageUpload/index.vue' //图片上传组件
import { computed } from 'vue'

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { bx_product_type, sys_scope, sys_status, bx_product_status, bx_smoking_allowed } =
  proxy.useDict(
    'bx_product_type',
    'sys_scope',
    'sys_status',
    'bx_product_status',
    'bx_smoking_allowed'
  )

const insurancePlanList = 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 queryRef = ref(null)
//在data中添加一个用于跟踪图片上传状态的变量
const imageUploaded = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: undefined
  },
  rules: {
    planName: [{ required: true, message: '产品计划名称不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    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 filteredRoleTypeOptions = computed(() => {
  //角色类型或者角色类型数组是否存在
  if (!sys_role_type.value || !Array.isArray(sys_role_type.value)) return []

  return sys_role_type.value.filter(option => {
    // 过滤掉超级管理员选项
    if (!option || typeof option.value === 'undefined') return false
    return Number(option.value) !== 1
  })
})

/** 查询角色列表 */
function getList() {
  loading.value = true
  getInsuranceProducPlanList(queryParams.value).then(response => {
    if (response.code === 200) {
      insurancePlanList.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 = []
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    planName: undefined
  }
  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 handleStatusChange(row) {
  const newStatus = row.status === 0 ? 0 : 1 // 获取切换后的新状态
  const text = newStatus === 0 ? '停用' : '启用' // 根据新状态显示文本
  proxy.$modal
    .confirm(`确认要${text}"${row.planName}"产品吗?`)
    .then(function () {
      return editPlanStatus(row.planBizId, newStatus).then(() => {
        proxy.$modal.msgSuccess(`${text}成功`)
        // 请求成功后，更新状态
        row.status = newStatus
        getList()
      })
    })
    .catch(() => {
      // 操作取消时恢复原状态
      row.status = row.status === 1 ? 0 : 1
      // 用户取消操作，保持原状态不变
      // 这里不需要做任何操作，因为switch会自动回滚
    })
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {}
  proxy.resetForm('roleRef')
}

/** 添加产品计划 */
function handleAdd() {
  form.value = {}
  open.value = true
  title.value = '添加产品计划'
}

/** 修改产品计划 */
function handleUpdate(row) {
  reset()
  const planBizId = row.planBizId
  getInsuranceProducPlanDetail(planBizId).then(response => {
    if (response.code === 200) {
      form.value = response.data
      open.value = true
      title.value = '修改产品计划'
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['roleRef'].validate(valid => {
    if (valid) {
      if (form.value.planBizId) {
        editInsuranceProducPlan(form.value).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      } else {
        addInsuranceProducPlan(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
  }
}
//========作用域-切换逻辑结束=========
// 添加图片变更处理函数
function handleImageChange(value) {
  imageUploaded.value = !!value
  // 手动触发表单验证
  if (proxy.$refs.form) {
    proxy.$refs.form.validateField('picture')
  }
}
</script>
<style lang="scss" scoped>
.logo-image {
  width: 70px;
  height: 70px;
  border-radius: 4px;
  object-fit: cover;
}
</style>
