<template>
  <div class="app-container">
    <CommonPage
      :operationBtnList="operationBtnList"
      :visibleDefaultButtons="visibleDefaultButtons"
      :showSearchForm="true"
      :show-pagination="true"
      :currentPage="queryParams.pageNo"
      :total="total"
      :pageSize="queryParams.pageSize"
      @current-change="changePageNo"
      @size-change="changePageSize"
    >
      <!-- 查询条件插槽 -->
      <template #searchForm>
        <el-form :model="queryParams" ref="queryRef" label-width="78px" label-position="top">
          <el-row :gutter="20">
            <el-col :sm="12" :lg="6" :xs="24">
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="dateRange"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @clear="clearDateRange"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="6" :xs="24">
              <el-form-item label="流程编号" prop="fnaNo">
                <el-input
                  v-model="queryParams.fnaNo"
                  placeholder="请输入流程编号"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="6" :xs="24">
              <el-form-item label="客户姓名" prop="customerName">
                <el-input
                  v-model="queryParams.customerName"
                  placeholder="请输入姓名"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>

            <el-col :sm="12" :lg="6" :xs="24">
              <el-form-item label="流程状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable>
                  <el-option
                    v-for="dict in csf_fna_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="6" :xs="24">
              <el-form-item label="创建人" prop="creatorName">
                <el-input
                  v-model="queryParams.creatorName"
                  placeholder="请输入创建人"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>

      <!-- 表格插槽 -->
      <template #table>
        <el-table
          v-loading="loading"
          :data="tenantList"
          @selection-change="tableSelect"
          @sort-change="sortChange"
          border
          max-height="380px"
        >
          <el-table-column type="index" width="100" label="序号" />
          <el-table-column label="客户姓名" align="center" prop="customerName" width="180">
            <template #default="scope">
              <el-button link size="default">
                <span @click="copyToClipboard(scope.row.customerName, '客户姓名')">{{
                  scope.row.customerName
                }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="中文姓名" align="center" prop="customerNameCn" width="180">
            <template #default="scope">
              <el-button link size="default">
                <span @click="copyToClipboard(scope.row.customerNameCn, '中文姓名')">{{
                  scope.row.customerNameCn
                }}</span>
              </el-button>
            </template>
          </el-table-column>
          <!-- <el-table-column label="状态" align="center" prop="status" width="100" :formatter="getDictLabel('csf_fna_status')"/> -->
          <el-table-column label="流程状态" sortable align="center" prop="status" width="200">
            <template #default="scope">
              <span>{{ selectDictLabel(csf_fna_status, scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="流程编号"
            align="center"
            prop="fnaNo"
            width="240"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-button link size="default">
                <span @click="copyToClipboard(scope.row.fnaNo, '流程编号')">{{
                  scope.row.fnaNo
                }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="预约编号"
            align="center"
            prop="appointmentNo"
            width="240"
            show-overflow-tooltip
          >
            <template #default="scope">
              <el-button link size="default">
                <span @click="copyToClipboard(scope.row.appointmentNo, '预约编号')">{{
                  scope.row.appointmentNo
                }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="保单号" align="center" prop="policyNo" width="180" />
          <el-table-column label="创建人" align="center" prop="creatorName" width="180" />

          <el-table-column label="创建时间" sortable align="center" prop="createTime" width="200">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-popover placement="left" :width="160" trigger="click">
                <template #reference>
                  <el-button link type="primary" size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                </template>
                <el-menu @select="index => handleSelect(index, row)" popper-class="custom-menu">
                  <el-menu-item
                    v-for="item in getVisibleDropdownItems(row)"
                    :index="item.value"
                    :key="item.value"
                  >
                    <el-text class="mx-1" v-if="!item.confirm">{{ item.label }}</el-text>
                    <el-popconfirm
                      v-else
                      confirm-button-text="Yes"
                      cancel-button-text="No"
                      :icon="InfoFilled"
                      icon-color="#626AEF"
                      :title="item.confirm"
                      @confirm="handleMenuConfirm(item.value, row)"
                      width="300"
                      placement="left-end"
                    >
                      <template #reference>
                        <el-text class="mx-1">{{ item.label }}</el-text>
                      </template>
                    </el-popconfirm>
                  </el-menu-item>
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </CommonPage>
    <!-- 下一步到预约 -->
    <div class="bottomBtn">
      <el-button type="primary" @click="goToAppointment">下一步</el-button>
    </div>
  </div>
</template>

<script setup name="FnaList">
import CommonPage from '@/components/commonPage'
import { getFnaList, deleteFna, subProcess } from '@/api/sign/fna'
import useUserStore from '@/store/modules/user'
import { MoreFilled, InfoFilled } from '@element-plus/icons-vue'
import useDictStore from '@/store/modules/dict'
import copyToClipboard from '@/utils/copyToClipboard'
const dictStore = useDictStore()
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { csf_fna_status } = proxy.useDict('csf_fna_status')

const tenantList = ref([])
const loading = ref(true)
const total = ref(0)
const dateRange = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    startTime: '',
    endTime: '',
    sortField: '',
    sortOrder: ''
  }
})

const { queryParams, form, rules } = toRefs(data)
// 控制要显示的默认按钮
const visibleDefaultButtons = ref(['add', 'query', 'reset']) // 只显示新增和查询两个默认按钮
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    label: '新建流程',
    direction: 'left',
    click: handleAdd
  },
  {
    key: 'reset',
    direction: 'right',
    click: resetQuery
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])
// 表格操作栏相关方法
// 基础菜单项配置（不使用 ref，因为它是静态的）
const baseDropdownItems = [
  { label: '修改', value: 'edit', confirm: '' },
  {
    label: '生成副本',
    value: 'copy',
    confirm: ''
  },
  {
    label: '删除',
    value: 'delete',
    confirm: '是否确认删除FNA流程？',
    // 只有当 row.status == 1 时才显示
    showCondition: row => !row.policyNo
  }
]
const getVisibleDropdownItems = row => {
  return baseDropdownItems.filter(item => {
    // 如果有 showCondition，则执行；否则默认显示
    return typeof item.showCondition === 'function' ? item.showCondition(row) : true
  })
}
// 菜单选择处理（无确认的操作）
const handleSelect = (index, row) => {
  // 只处理不需要确认的操作
  const item = baseDropdownItems.find(i => i.value === index)
  if (item && !item.confirm) {
    handleMenuAction(index, row)
  }
  // 如果有 confirm，则由 el-popconfirm 触发 handleMenuConfirm
}

// 带确认的操作（由 popconfirm 触发）
const handleMenuConfirm = (value, row) => {
  handleMenuAction(value, row)
}

// 统一处理菜单动作
const handleMenuAction = (action, row) => {
  switch (action) {
    case 'edit':
      handleUpdate(row)
      break
    case 'copy':
      handleCopy(row)
      break
    case 'delete':
      if (!row.policyNo) {
        handleDelete(row)
      }

      break
    default:
      proxy.$message.info('功能暂未开放')
  }
}
const changePageNo = val => {
  queryParams.value.pageNo = val
  getList()
}
const changePageSize = val => {
  queryParams.value.pageSize = val
  getList()
}
const clearDateRange = () => {
  dateRange.value = []
}
const handleCopy = row => {
  subProcess({ fnaBizId: row.fnaBizId }).then(response => {
    if (response.code === 200) {
      getList()
      proxy.$modal.msgSuccess('生成副本成功')
    }
  })
}
const sortChange = ({ prop, order }) => {
  if (order == 'ascending') {
    queryParams.value.sortOrder = 'ascend'
  } else {
    queryParams.value.sortOrder = 'descend'
  }
  if (prop) {
    queryParams.value.sortField = prop
  }
  getList()
}
/** 多选框选中数据 */
function tableSelect(selection) {
  // selectIdsList.value = selection.map(item => item.projectBizId)
}
const goToAppointment = () => {
  router.push({ path: '/sign/appointment' })
}
/** 查询租户列表 */
function getList() {
  if (dateRange.value.length > 0) {
    queryParams.value.startTime = `${dateRange.value[0]} 00:00:00`
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`
  } else {
    queryParams.value.startTime = ''
    queryParams.value.endTime = ''
  }
  loading.value = true
  try {
    getFnaList(queryParams.value).then(response => {
      tenantList.value = response.data.records
      total.value = response.data.total
      loading.value = false
    })
  } catch (error) {
    tenantList.value = []
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    startTime: '',
    endTime: ''
  }
  handleQuery()
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    let res = await deleteFna({ fnaBizId: row.fnaBizId })
    if (res.code === 200) {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    }
  } catch (error) {
    console.log('error', error)
  }
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/sign/FnaList/edit?type=add')
}

/** 修改按钮操作 */
function handleUpdate(row) {
  router.push({
    path: '/sign/FnaList/edit',
    query: {
      fnaBizId: row.fnaBizId,
      type: 'edit',
      status: row.status,
      source: 'fnaList',
      appointmentBizId: row.appointmentBizId
    }
  })
}

getList()
</script>
<style lang="scss" scoped>
.bottomBtn {
  box-sizing: border-box;
  width: 100%;
  text-align: right;
  margin-top: 20px;
  /* position: fixed;
  bottom: 0;
  background-color: #fff;
  z-index: 999;
  border-top: 1px solid rgb(247 247 247);
  padding: 10px 20px; */
}
</style>
