<template>
  <div class="app-container">
    <CommonPage
      :operationBtnList="operationBtnList"
      :showSearchForm="true"
      :show-pagination="false"
    >
      <!-- 查询条件插槽 -->
      <template #searchForm>
        <el-form :model="queryParams" ref="queryRef" label-width="100px">
          <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"
        >
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column label="预约编号" align="center" prop="appointmentNo" width="200" />
          <el-table-column label="预约状态" align="center">
            <template #default="scope">
              <dict-tag :options="csf_ap_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="最终预约时间" align="center" width="180">
            <template #default="scope">
              <span>{{
                scope.row.confirmAppointmentTime
                  ? parseTime(scope.row.confirmAppointmentTime)
                  : '--'
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="productName" width="150" />
          <el-table-column label="保险公司" align="center" prop="companyName" width="150" />
          <el-table-column
            label="业务员"
            align="center"
            prop="businessRepresentName1"
            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="paymentTerm" width="100" />
          <el-table-column label="每期保费" align="center" prop="eachIssuePremium" width="100" />

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

          <el-table-column
            label="意向预约时间"
            align="center"
            prop="intentionAppointmentTime"
            width="240"
            show-overflow-tooltip
          >
            <template #default="scope">
              <span>{{
                scope.row.intentionAppointmentTime
                  ? parseTime(scope.row.intentionAppointmentTime)
                  : '--'
              }}</span>
            </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
            label="操作"
            align="left"
            width="250"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button
                link
                type="primary"
                v-if="scope.row.status == 2 || scope.row.status == 3"
                @click="getAppointmentInfo(scope.row.appointmentBizId)"
                >查看行程单</el-button
              >
              <el-button link type="primary" @click="handleExprot(scope.row)">导出</el-button>
              <el-button
                link
                type="danger"
                v-if="scope.row.status === 0"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div style="width: 100%; display: flex; justify-content: flex-end; margin-bottom: 30px">
          <pagination
            v-show="total >= 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </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 CommonPage from '@/components/commonPage'
import DetailPanel from '@/components/DetailPanel'
import { onMounted, onActivated, ref } from 'vue'
import CommonDialog from '@/components/commonDialog'
import {
  getAppointmentList,
  getAppointmentExprot,
  delSigleAppointment,
  getItineraryDetail,
  getItineraryExprot
} from '@/api/sign/appointment'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const dialogVisible = ref(false)
const appointmentSummeryInfo = ref({})
const tenantList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const dateRange = ref([])
const detailData = ref([]) //行程单-行程信息
const exportLoading = ref(false)
const operationBtnList = ref([
  {
    label: '搜索',
    icon: 'Search',
    type: 'primary',
    direction: 'right',
    size: 'small',
    click: handleQuery
  },
  {
    label: '重置',
    icon: 'Refresh',
    type: 'info',
    direction: 'right',
    size: 'small',
    click: resetQuery
  }
])
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 } = proxy.useDict(
  'bx_currency_type',
  'csf_ap_status',
  'csf_ap_meeting_point'
)
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) {
  // 对预约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'
  }
  router.push({
    path: '/sign/appointment/appointmentEdit',
    query: data
  })
}

getList()
</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 {
  padding: 0 15px;
  .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>
