<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="100px" label-position="top">
          <el-row :gutter="30">
            <el-col :sm="12" :lg="8" :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="clearDate"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="8" :xs="24">
              <el-form-item label="预约编号" prop="appointmentNo">
                <el-input
                  v-model="queryParams.appointmentNo"
                  placeholder="请输入预约编号"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="8" :xs="24">
              <el-form-item label="预约状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择" clearable>
                  <el-option
                    v-for="dict in csf_ap_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </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"
          max-height="380px"
        >
          <el-table-column type="index" label="序号" width="60" fixed="left" />
          <el-table-column
            label="预约编号"
            align="center"
            prop="appointmentNo"
            width="200"
            fixed="left"
          />
          <el-table-column label="预约状态" align="center" prop="status" fixed="left" width="100">
            <template #default="scope">
              <dict-tag :options="csf_ap_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="产品名称"
            align="center"
            prop="productName"
            width="200"
            show-overflow-tooltip
          />
          <el-table-column label="签单日" align="center" width="180" prop="signDate">
            <template #default="scope">
              <span>{{ scope.row.signDate ? formatToDate(scope.row.signDate) : '--' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="保险公司" align="center" prop="companyName" width="150" />
          <el-table-column label="签单员" align="center" prop="signName" width="150" />

          <el-table-column label="投保人" align="center" prop="policyholder" width="150" />
          <el-table-column label="受保人" align="center" prop="insurant" width="150" />
          <!-- <el-table-column label="供款频率" align="center" prop="paymentFrequency" width="100">
            <template #default="scope">
              <dict-tag :options="csf_ap_frequency" :value="scope.row.paymentFrequency" />
            </template>
          </el-table-column> -->
          <el-table-column label="供款频率" align="center" width="150" prop="paymentFrequency">
            <template #default="scope">
              <dict-tag :options="csf_ap_frequency" :value="scope.row.paymentFrequency" />
            </template>
          </el-table-column>
          <el-table-column label="供款期数" align="center" prop="paymentTerm" width="100" />
          <el-table-column label="每期保费" align="center" prop="eachIssuePremium" width="100" />

          <el-table-column label="保单币种" align="center" width="150" prop="currency">
            <template #default="scope">
              <dict-tag :options="bx_currency_type" :value="scope.row.currency" />
            </template>
          </el-table-column>

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

          <el-table-column fixed="right" label="操作" width="80" 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="success" @click="goToAppointment('previousStep')">上一步</el-button>
      <el-button type="primary" @click="goToAppointment('nextStep')">下一步</el-button>
    </div>

    <CommonDialog
      dialogTitle="香港行程安排"
      confirmText="下载行程单"
      cancleText="关闭"
      dialogWidth="70%"
      :openDialog="dialogVisible"
      @confirm="handleExprotPdf"
      @close="dialogVisible = false"
    >
      <div class="dialogBox">
        <div class="dialogItem" v-for="item in detailData">
          <div class="dialogItemTitle">{{ item.title }}</div>
          <DetailPanel
            :data="item.data"
            :row-span="24"
            col-gap="10px"
            label-width="120px"
            row-height="45px"
            :show-col-border="true"
          />
        </div>
        <div class="remarkBOx">
          <div class="remarkTitle">备注</div>
          <div class="remarkContent" v-if="appointmentSummeryInfo.remark">
            {{ appointmentSummeryInfo.remark }}
          </div>
          <div class="remarkEmpty" v-else>暂无备注</div>
        </div>
      </div>
    </CommonDialog>
  </div>
</template>

<script setup name="Appointment">
import { MoreFilled, InfoFilled } from '@element-plus/icons-vue'

import CommonPage from '@/components/commonPage'
import DetailPanel from '@/components/DetailPanel'
import { onMounted, onActivated, ref } from 'vue'
import CommonDialog from '@/components/commonDialog'
import useDictStore from '@/store/modules/dict'
import {
  getAppointmentList,
  getAppointmentExprot,
  delSigleAppointment,
  getItineraryDetail,
  getItineraryExprot
} from '@/api/sign/appointment'
import useUserStore from '@/store/modules/user'
const dictStore = useDictStore()
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const dialogVisible = ref(false)
const appointmentSummeryInfo = ref({})
const tenantList = ref([])
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const dateRange = ref([])
const detailData = ref([]) //行程单-行程信息
const exportLoading = ref(false)
// 控制要显示的默认按钮
const visibleDefaultButtons = ref(['query', 'reset']) // 只显示新增和查询两个默认按钮
// 按钮配置
const operationBtnList = ref([
  {
    key: 'reset',
    direction: 'right',
    click: resetQuery
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])

const changePageNo = val => {
  queryParams.value.pageNo = val
  getList()
}
const changePageSize = val => {
  queryParams.value.pageSize = val
  getList()
}
const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    startTime: '',
    endTime: ''
  }
})

const { queryParams, form, rules } = toRefs(data)
const { bx_currency_type, csf_ap_status, csf_ap_meeting_point, csf_ap_frequency } = proxy.useDict(
  'bx_currency_type',
  'csf_ap_status',
  'csf_ap_meeting_point',
  'csf_ap_frequency'
)
// 基础菜单项配置（不使用 ref，因为它是静态的）
const baseDropdownItems = [
  { label: '修改', value: 'edit', confirm: '' },
  {
    label: '生成行程单',
    value: 'viewItinerary',
    confirm: '',
    // 只有当 row.status == 1 时才显示
    showCondition: row => row.status == 1
  }
]
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 'viewItinerary':
      if (row.status !== 0) {
        handleUpdate(row, 'viewItinerary')
      }
      break
    case 'delete':
      if (row.status !== 0) {
        proxy.$message.warning('仅“待提交”状态的预约可删除')
        return
      }
      handleDelete(row)
      break
    default:
      proxy.$message.info('功能暂未开放')
  }
}
const handleExprotPdf = () => {
  exportLoading.value = true
  getItineraryExprot(appointmentSummeryInfo.value.appointmentBizId).then(res => {
    if (res.code == 200) {
      // 创建隐藏的下载链接
      const link = document.createElement('a')
      link.href = res.data
      link.target = '_blank' // 新窗口打开

      // 设置下载文件名（重要）
      // 从URL中提取文件名，或者使用返回的文件名
      const fileName = `香港行程安排.pdf`
      link.download = fileName

      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      exportLoading.value = false
      dialogVisible.value = false
    } else {
      proxy.$message.error('行程单下载失败')
      exportLoading.value = false
    }
  })
}
// 获取预约详情
function getAppointmentInfo(appointmentBizId) {
  getItineraryDetail(appointmentBizId).then(res => {
    if (res.code == 200) {
      appointmentSummeryInfo.value = res.data
      appointmentSummeryInfo.value.appointmentBizId = appointmentBizId
      csf_ap_meeting_point._object.csf_ap_meeting_point.forEach(item => {
        if (item.value == appointmentSummeryInfo.value.meetingPoint) {
          appointmentSummeryInfo.value.meetingPoint = item.label
        }
      })
      if (appointmentSummeryInfo.value.total) {
        appointmentSummeryInfo.value.total = Number(appointmentSummeryInfo.value.total).toFixed(2)
      }

      detailData.value = [
        {
          title: '集合信息',
          data: [
            // 第一行：2列布局（各占12）
            {
              label: '集合时间',
              value: appointmentSummeryInfo.value.arrivalTime,
              span: 12 // 占12/24
            },
            {
              label: '预约时间',
              value: appointmentSummeryInfo.value.confirmAppointmentTime,
              span: 12 // 占12/24
            },
            {
              label: '集合地点',
              value: appointmentSummeryInfo.value.meetingPoint,
              span: 12 // 占12/24
            },
            {
              label: '意向地点',
              value: appointmentSummeryInfo.value.signingAddress,
              span: 12 // 占12/24
            }
          ]
        },
        {
          title: '业务代表',
          data: [
            // 第一行：2列布局（各占12）
            {
              label: '姓名',
              value: appointmentSummeryInfo.value.businessRepresentName1,
              span: 12 // 占12/24
            },
            {
              label: '联系电话',
              value: appointmentSummeryInfo.value.businessRepresentMobile1
                ? appointmentSummeryInfo.value.businessRepresentMobile1Code +
                  appointmentSummeryInfo.value.businessRepresentMobile1
                : '-',
              span: 12 // 占12/24
            }
          ]
        },
        {
          title: '咨询内容',
          data: [
            // 第一行：2列布局（各占12）
            {
              label: '咨询人',
              value: appointmentSummeryInfo.value.name,
              span: 12 // 占12/24
            },
            // {
            //   label: '受保人',
            //   value: appointmentSummeryInfo.value.insurantName,
            //   span: 12 // 占12/24
            // },
            {
              label: '意向缴费年期',
              value: appointmentSummeryInfo.value.paymentTerm,
              span: 12 // 占12/24
            },
            {
              label: '保单征费',
              value: appointmentSummeryInfo.value.policyFee || '-',
              span: 12 // 占12/24
            },
            {
              label: '币种',
              value: appointmentSummeryInfo.value.currency,
              span: 12 // 占12/24
            },
            {
              label: '意向咨询产品',
              value: appointmentSummeryInfo.value.productName,
              span: 12 // 占12/24
            },
            {
              label: '合计金额',
              value: appointmentSummeryInfo.value.total,
              span: 12 // 占12/24
            }
          ]
        }
      ]

      dialogVisible.value = true
    }
  })
}
const handleExprot = async row => {
  try {
    const res = await getAppointmentExprot(row.appointmentBizId)
    if (res.code == 200) {
      // 创建隐藏的下载链接
      const link = document.createElement('a')
      link.href = res.data.url
      // link.target = '_blank' // 新窗口打开

      // 设置下载文件名（重要）
      // 从URL中提取文件名，或者使用返回的文件名
      const fileName = '预约导出.xlsx'
      link.download = fileName

      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      proxy.$message.success('导出成功')
    }
  } catch (error) {
    console.error('导出失败:', error)
  }
}
const clearDate = () => {
  dateRange.value = []
  queryParams.value.startTime = ''
  queryParams.value.endTime = ''
}
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 = type => {
  if (type == 'previousStep') {
    router.push({ path: '/sign/FnaList' })
  } else if (type == 'nextStep') {
    router.push({ path: '/sign/underwritingMain' })
  }
}
/** 查询租户列表 */
function getList() {
  if (dateRange.value && dateRange.value.length > 0) {
    queryParams.value.startTime = `${dateRange.value[0]} 00:00:00`
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`
  }
  loading.value = true
  try {
    getAppointmentList(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()
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除' + row.creatorName + '的预约流程？')
    .then(function () {
      return delSigleAppointment(row.appointmentBizId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
/** 修改按钮操作 */
function handleUpdate(row, type) {
  // 对预约status进行转换，到编辑页面在转换会有时机问题
  csf_ap_status._object.csf_ap_status.forEach(element => {
    element.value = Number(element.value)
    if (row.status == element.value) {
      row.status = element.label
    }
  })
  let status = row.status
  let data = {
    status: status,
    createTime: row.createTime,
    appointmentNo: row.appointmentNo,
    creatorName: row.creatorName,
    appointmentBizId: row.appointmentBizId,
    source: 'appointmentList'
  }
  // 以生成行程单的方式进入到预约详情
  if (type == 'viewItinerary') {
    data.appointmentType = '2'
  }
  router.push({
    path: '/sign/appointment/appointmentEdit',
    query: data
  })
}

getList()
// 请求一下字典值方便表单回显
if (dictStore.dictTypeLists.length == 0) {
  proxy.useDictLists([
    'csf_employment',
    'sys_no_yes',
    'bx_currency_type',
    'csf_liquid_asset_type',
    'csf_premium_funding_source',
    'csf_customer_type',
    'csf_customer_title',
    'sys_gender',
    'csf_marriage',
    'csf_education',
    'csf_id_type',
    'csf_ap_apply_type',
    'csf_ap_meeting_point',
    'csf_ap_first_issue',
    'csf_ap_dividend',
    'csf_ap_frequency',
    'csf_ap_rel',
    'csf_ap_registration',
    'csf_ap_exercise',
    'csf_ap_risk',
    'csf_ap_movie',
    'csf_ap_game',
    'csf_ap_policy_transfer',
    'wj_question_first_category',
    'wj_question_second_category',
    'csf_ap_status',
    'md_bank',
    'oss_data_type',
    'oss_data_person'
  ])
}
</script>
<style lang="scss" scoped>
.app-container {
  box-sizing: border-box;
}
.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; */
}
.dialogBox {
  .dialogTitle {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
  .dialogItem {
    .dialogItemTitle {
      font-size: 16px;
      font-weight: 500;
      margin: 10px 0;
      color: #333;
    }
  }
  .remarkBOx {
    padding: 10px;
    box-sizing: border-box;
    background-color: #f5f5f5;
    border-radius: 5px;
    .remarkTitle {
      font-size: 16px;
    }
    .remarkEmpty {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      margin-bottom: 10px;
    }
  }
  .exprotBtn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
