<template>
  <div class="app-container">
    <!-- 步骤条 -->
    <!-- <el-row style="margin-bottom: 30px">
      <el-col :span="24">
        <Step :stepList="stepList"></Step>
      </el-col>
    </el-row> -->
    <!-- 条件查询 -->
    <el-row>
      <el-col :span="24">
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="确认预约时间" style="width: 300px">
            <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-form-item label="预约编号" prop="appointmentNo">
            <el-input
              v-model="queryParams.appointmentNo"
              placeholder="请输入预约编号"
              clearable
              style="width: 150px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="预约状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择"
              clearable
              style="width: 110px"
            >
              <el-option
                v-for="dict in csf_ap_status"
                :key="dict.value"
                :label="dict.label"
                :value="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-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tenantList"
      @selection-change="tableSelect"
      @sort-change="sortChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <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" 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="time" width="240" show-overflow-tooltip>
      </el-table-column>
      <!-- sortable -->
      <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>
    <pagination
      v-show="total >= 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 下一步到预约 -->
    <div class="bottomBtn">
      <el-button type="success" @click="goToAppointment('previousStep')">上一步</el-button>
      <el-button type="primary" @click="goToAppointment('nextStep')">下一步</el-button>
    </div>
    <!-- 展示行程单详情 -->
    <el-dialog v-model="dialogVisible" width="70%">
      <div class="dialogBox">
        <div class="dialogTitle">香港行程安排</div>
        <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 class="exprotBtn">
          <el-button
            :loading="exportLoading"
            type="primary"
            style="margin-top: 15px"
            @click="handleExprotPdf"
            >下载行程单</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Appointment">
import DetailPanel from '@/components/DetailPanel'
import { onMounted, onActivated, ref } from 'vue'
import Step from '@/views/components/moduleStep'
import {
  getAppointmentList,
  getAppointmentExprot,
  delSigleAppointment,
  getItineraryDetail,
  getItineraryExprot
} from '@/api/sign/appointment'
import useUserStore from '@/store/modules/user'
const stepList = ref([
  { title: 'FNA', id: 1, finish: true, todo: false, unFinish: false },
  { title: '预约', id: 2, todo: true, finish: false, unFinish: false },
  { title: '新单跟进', id: 3, finish: false, todo: false, unFinish: true }
])
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 data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 8,
    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
      // proxy.$message.success('行程单下载成功')
      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: 8,
    startTime: '',
    endTime: ''
  }
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除' + row.creatorName + '的预约流程？')
    .then(function () {
      return delSigleAppointment(row.appointmentBizId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 重置操作表单 */
function reset() {
  form.value = {
    pageNo: 1,
    pageSize: 8
  }
  proxy.resetForm('tenantRef')
}

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

/** 修改按钮操作 */
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>
/* ::v-deep .el-step__head.is-success {
  color: none !important;
  background-color: #e8f3ff !important;
  border: none !important;
} */
/* ::v-deep .el-step__icon {
 background-color: #e8f3ff !important;
} */
.bottomBtn {
  width: 100%;
  text-align: right;
  margin-top: 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>
