<template>
  <Modal v-model="visible" title="回访历史" width="900">
    <div>
      <div v-if="useRecord">
        <h4 class="section-title">人员基本信息</h4>
        <Form :label-width="100" inline class="info-form">
          <FormItem label="姓名"><Input :value="detail.name || '-'" disabled style="width: 220px" /></FormItem>
          <FormItem label="性别"><Input :value="renderSex(detail.sex)" disabled style="width: 220px" /></FormItem>
          <FormItem label="身份证号"><Input :value="detail.card_no || '-'" disabled style="width: 220px" /></FormItem>
          <FormItem label="民族"><Input :value="renderFolk(detail.folk) || '-'" disabled style="width: 220px" /></FormItem>
          <FormItem label="本人联系方式"><Input :value="detail.phone || '-'" disabled style="width: 220px" /></FormItem>
          <FormItem label="现住址" style="width: 100%">
            <Input :value="`${detail.city || '-'} / ${detail.area || '-'} / ${detail.street || '-'} / ${detail.community || '-'}`" disabled />
          </FormItem>
        </Form>

        <div v-if="String(detail.do_status) === '1'">
          <h4 class="section-title">本次回访信息</h4>
          <Form :label-width="100">
            <FormItem label="风险等级"><Input :value="renderRatingType(detail.rating_type)" disabled /></FormItem>
            <FormItem label="回访人"><Input :value="detail.visit_user || '-'" disabled /></FormItem>
            <FormItem label="回访时间"><Input :value="formatDateTime(detail.visit_time)" disabled /></FormItem>
            <FormItem label="回访记录"><Input type="textarea" :rows="4" :value="detail.visit_record || '-'" disabled /></FormItem>
            <FormItem label="回访图片">
              <div class="img-list">
              <img v-for="(src,idx) in (detail.img && (Array.isArray(detail.img) ? detail.img : String(detail.img).split(',').map(s=>s.trim()).filter(Boolean)))" :key="idx" :src="src" style="width:80px;height:80px;margin-right:8px" @click="openImagePreview(src)" />
              </div>
            </FormItem>
          </Form>
        </div>
      </div>

      <h4 class="section-title">历史回访信息</h4>
      <Table :columns="visitHistoryColumns" :data="historyData" border style="width: 100%" class="history"/>
      <Page class="page_style" :total="page.totalRecord" :current="page.pageNo" :page-size="page.pageSize" show-total show-sizer @on-change="changePageNo" @on-page-size-change="changePageSize" />
    </div>
    <div slot="footer">
      <Button type="primary" @click="visible=false">关闭</Button>
    </div>

    <!-- 回访详情弹窗（查看） -->
    <Modal v-model="recordModal.visible" title="回访详情" width="680">
      <div>
        <Form :label-width="100">
          <FormItem label="风险等级"><Input :value="renderRatingType(recordModal.data.rating_type)" disabled /></FormItem>
          <FormItem label="回访时间"><Input :value="formatDateTime(recordModal.data.visit_time)" disabled /></FormItem>
          <FormItem label="回访人"><Input :value="recordModal.data.visit_user || recordModal.data.do_user_name || recordModal.data.operator_name || recordModal.data.create_user_name || '-'" disabled /></FormItem>
          <FormItem label="回访记录"><Input type="textarea" :rows="4" :value="recordModal.data.visit_record || '-'" disabled /></FormItem>
          <FormItem label="回访图片">
            <!-- <div class="img-list">
              <img v-for="(src,idx) in recordModalImgs" :key="idx" :src="src" style="width:80px;height:80px;margin-right:8px" @click="openImagePreview(src)" />
            </div> -->
            <span
              class="demo-upload-list"
              v-for="(item, index) in preview_imgs"
              :key="index"
            >
              <span class="hover-effect" @click="checkFile(item,index)">
               图片{{index+1}}-{{item.originalFilename}}
              </span>
            </span>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" @click="recordModal.visible=false">关闭</Button>
      </div>
    </Modal>
    <!-- 图片预览（全屏） -->
    <Modal v-model="imagePreview.visible" title="图片预览" :footer-hide="true" fullscreen :mask-closable="true">
      <div style="height: calc(100vh - 100px); display: flex; align-items: center; justify-content: center;">
        <img :src="imagePreview.src" style="max-width: 100%; max-height: 100%;" />
      </div>
    </Modal>
    <CImage ref="cImageRef" />
  </Modal>
</template>

<script>
import { getVisitRecordDetail, selectVisitHistoryPage } from '@/api/key-person'
import { getDictList } from '@/api/common'
import { findMZList } from '@/api/peopleInfo'
import axios from 'axios'
import CImage from '_c/c-image/index.vue'
export default {
  name: 'VisitHistoryModal',
  components: { CImage },
  props: {
    rating_dict_type: { type: String, required: true },
    key_person_id: { type: [String, Number], default: '' },
    jl_key_person_visit_record_id: { type: [String, Number], default: '' }
  },
  data () {
    return {
      visible: false,
      detail: {},
      historyData: [],
      page: { pageNo: 1, pageSize: 10, totalRecord: 0 },
      visitHistoryColumns: [
        { title: '风险等级', key: 'rating_type', align: 'center', width: 120, render: (h, { row }) => h('span', this.renderRatingType(row.rating_type)) },
        { title: '回访时间', key: 'visit_time', align: 'center', width: 180, render: (h, { row }) => h('span', this.formatDateTime(row.visit_time)) },
        { title: '回访人', key: 'visit_user', align: 'center', width: 120 },
        { title: '操作', key: 'action', align: 'center', width: 100, render: (h, { row }) => h('Button', { props: { type: 'primary', size: 'small' }, on: { click: () => this.openRecord(row) } }, '详情') }
      ],
      ratingTypeOptions: [],
      nationMap: {},
      recordModal: { visible: false, data: {} },
      imagePreview: { visible: false, src: '' },
      suffixList: ['jpg', 'jpeg', 'png'],
      preview_imgs: []
    }
  },
  computed: {
    useRecord () { return !!this.jl_key_person_visit_record_id }
  },
  created () {
    this.loadDicts()
  },
  methods: {
    open () {
      this.page.pageNo = 1
      if (this.useRecord) {
        this.openByRecord()
      } else if (this.key_person_id) {
        this.openByPerson()
      } else {
        this.$Notice.error({ title: '缺少参数', desc: '请传入 key_person_id 或 jl_key_person_visit_record_id' })
        return
      }
      this.visible = true
    },
    openByRecord () {
      const payload = { id: this.jl_key_person_visit_record_id, rating_dict_type: String(this.rating_dict_type || '') }
      getVisitRecordDetail(payload).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const d = ret.data.data || {}
          this.detail = d
          this.fetchHistory({ key_person_id: d.key_person_id, exclude_id: d.current_visit_record_id || d.id })
        }
      })
    },
    openByPerson () {
      // 仅查询历史，不显示本次回访信息
      this.detail = {}
      this.fetchHistory({ key_person_id: this.key_person_id, order_by: 'visit_time desc' })
    },
    fetchHistory (extraParams) {
      const params = Object.assign(
        {},
        extraParams,
        { rating_dict_type: String(this.rating_dict_type || '') }
      )
      const payload = { params, pageNo: this.page.pageNo, pageSize: this.page.pageSize }
      selectVisitHistoryPage(payload).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const page = ret.data.data || { results: [], totalRecord: 0 }
          this.page.totalRecord = page.totalRecord || 0
          this.historyData = (page.results || []).map(it => ({
            rating_type: it.rating_type,
            visit_user: it.visit_user,
            visit_user_company: it.visit_user_company,
            visit_time: it.visit_time,
            visit_record: it.visit_record,
            img: it.img,
            do_status: it.do_status
          }))
        }
      })
    },
    changePageNo (pageNo) { this.page.pageNo = pageNo; this.reloadHistory() },
    changePageSize (pageSize) { this.page.pageSize = pageSize; this.changePageNo(1) },
    reloadHistory () {
      if (this.useRecord) {
        const d = this.detail || {}
        this.fetchHistory({ key_person_id: d.key_person_id, exclude_id: d.current_visit_record_id || d.id })
      } else if (this.key_person_id) {
        this.fetchHistory({ key_person_id: this.key_person_id, order_by: 'visit_time desc' })
      }
    },
    openImagePreview (src) {
      if (!src) return
      this.imagePreview.src = src
      this.imagePreview.visible = true
    },
    openRecord (row) {
      console.log('visitdetail', row)
      this.preview_imgs = []
      this.recordModal.data = Object.assign({}, row)
      this.recordModal.visible = true
      this.recordModalImgs()
    },
    recordModalImgs () {
      const data = this.recordModal && this.recordModal.data ? this.recordModal.data : {}
      const img = data.img
      if (!img) return []
      let imgs = []
      try {
        imgs = JSON.parse(img)
      } catch (e) {
        imgs = []
      }
      console.log('imgs', imgs)
      if (imgs.length > 0) {
        imgs.forEach(img => {
          this.getImgUrl(img.uuid, img.suffix, img.originalFilename, img.url)
        })
      }
    },
    loadDicts () {
      getDictList({ type: 'rating_level' }).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const results = ret.data.data && ret.data.data.results ? ret.data.data.results : []
          this.ratingTypeOptions = results.map(it => ({ label: it.label || it.name, value: it.value || it.dictValue }))
        }
      })
      findMZList().then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const list = ret.data.data || []
          const map = {}
          list.forEach(it => { if (it && (it.mzcode || it.value)) { map[String(it.mzcode || it.value)] = it.mzname || it.label || it.name } })
          this.nationMap = map
        }
      })
    },
    renderVisitStatus (val) {
      const s = String(val)
      if (s === '2') return '超期未回访'
      if (s === '1') return '已回访'
      return '待回访'
    },
    renderRatingType (val) {
      const found = this.ratingTypeOptions.find(it => it.value === val)
      return found ? found.label : val || '-'
    },
    renderSex (s) { return s === '1' ? '男' : s === '2' ? '女' : '-' },
    renderFolk (val) {
      if (val === null || val === undefined || val === '') return '-'
      const v = String(val)
      return this.nationMap[v] || v
    },
    formatDateTime (val) {
      if (!val) return '-'
      const d = new Date(val)
      if (Number.isNaN(d.getTime())) {
        const m = /^(\d{4}-\d{2}-\d{2})[ T]?(\d{2}:\d{2}:\d{2})?/.exec(String(val))
        if (m) return `${m[1]}${m[2] ? ' ' + m[2] : ' 00:00:00'}`
        return String(val)
      }
      const y = d.getFullYear()
      const mm = String(d.getMonth() + 1).padStart(2, '0')
      const dd = String(d.getDate()).padStart(2, '0')
      const HH = String(d.getHours()).padStart(2, '0')
      const MM = String(d.getMinutes()).padStart(2, '0')
      const SS = String(d.getSeconds()).padStart(2, '0')
      return `${y}-${mm}-${dd} ${HH}:${MM}:${SS}`
    },
    checkFile (item, index) {
      console.log('item, index>>', item, index)
      // window.open
      if (this.suffixList.includes(item.suffix)) {
        this.$refs.cImageRef.init({ src: item.url })
      } else {
        window.open(item.url, '_blank')
      }
      console.log(item, index)
    },
    getImgUrl (uuid, suffix, originalFilename, imgurl) {
      let that = this
      axios({
        method: 'get',
        responseType: 'arraybuffer',
        url:
          '/api/ac/jilinsscgsdp/uploadService/getObsObject?uuid=' +
          uuid +
          '&&suffix=' +
          suffix
      }).then(function (res) {
        // 构建完整的附件对象，包含所有必要信息
        let fileObj = {
          uuid: uuid,
          suffix: suffix,
          originalFilename: originalFilename,
          url: imgurl
        }
        if (that.suffixList.includes(suffix)) {
          const base64String = btoa(
            new Uint8Array(res.data).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ''
            )
          )
          fileObj.url = 'data:image/png;base64,' + base64String
        } else {
          fileObj.url = res.data
        }
        that.preview_imgs.push(fileObj)
        // 调用下载方法，把后端传过来的流传给fileDownload方法
        // this.fileDownload(res.data, fileName)
      })
    }
  }
}
</script>

<style scoped>
.section-title { margin: 10px 0; font-weight: 600; }
.info-form { margin-bottom: 8px; }
.img-list { margin-top: 8px; }
.img-list img { cursor: pointer; object-fit: cover; }
::v-deep .history table {
  width: 100% !important;
  border-collapse: collapse;
}
.hover-effect {
  cursor: pointer; /* 小手效果 */
  transition: all 0.3s ease; /* 添加过渡效果使变化更平滑 */
}

.hover-effect:hover {
  color: #1890ff; /* 文字变蓝色 */
  background-color: #e6f7ff; /* 背景变浅蓝色 */
  border-color: #1890ff; /* 边框变蓝色 */
}
</style>
