<template>
  <div class="contradiction-div">
    <!--    <div class="title-style">APP通知信息</div>-->
    <Form :model="formInline" ref="form" label-position="left" :label-width="80">
      <Row>
        <Col span="12" offset="6">
          <FormItem label="标题：" prop="title" :rules="[{required: true, message: '必填', trigger: 'blur' }]">
            <Input v-model="formInline.title" :disabled="isReadOnly" type="text" placeholder="请输入标题"></Input>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col offset="6" span="12">
          <FormItem :rules="[{required: true, message: '必填', trigger: 'blur' }]" label="信息类型" prop="category">
            <Select v-model="formInline.category" :disabled="isReadOnly" placeholder="请选择信息类型" @on-change="handleSelect">
              <Option v-for="item in options2" :key="item.value" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col span="12" offset="6">
          <FormItem label="内容：" prop="context" :rules="[{required: true, message: '必填', trigger: 'blur' }]">
            <div class="ql-editor" v-if="isReadOnly" v-html="formInline.context"></div>
            <wl-vue2-editor v-else v-model="formInline.context" :noImage="true"></wl-vue2-editor>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col span="12" offset="6">
          <FormItem label="发布范围" prop="areaList" required>
            <treeselect
              ref="treeSelectRef"
              v-model="formInline.areaList"
              :disabled="isReadOnly"
              :load-options="loadOptions"
              :multiple="true"
              :normalizer="normalizer"
              :options="options"
              :show-count="false"
              :valueFormat="valueFormat"
              placeholder="选择发布范围"
            />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col span="4" offset="6" >
          <FormItem label="上传附件">
            <Upload
              action="#"
              :before-upload="beforeUpload"
              :show-upload-list="false"
            >
              <Button v-if="!isReadOnly" icon="ios-cloud-upload-outline">上传附件</Button>
            </Upload>
          </FormItem>
        </Col>
        <Col span="4" v-if="imgArr.length !== 0" :key="index" v-for="(item, index) in imgArr">
          <span class="hover-effect" @click="checkFile(item,index)">
           附件{{index+1}}-{{item.originalFilename}}
          </span>
          <span style="margin-left: 10px;cursor: pointer;" @click="delFile(item,index)" v-if="!isReadOnly">
            <Icon type="md-close" />
          </span>
        </Col>
      </Row>

      <!--      <Row>-->
      <!--        <Col span="12" offset="6">-->
      <!--          <FormItem label="排序：" prop="sort" :rules="[{required: true, message: '必填', trigger: 'change'}]">-->
      <!--            <Input v-model="formInline.sort" :disabled="isReadOnly" type="number" placeholder="请输入排序"></Input>-->
      <!--          </FormItem>-->
      <!--        </Col>-->
      <!--      </Row>-->
      <Row>
        <Col span="12" offset="6">
          <div  v-if="!isReadOnly">
            <!--            <Button type="primary" class="mr10" @click="getSelectedTreeNodes">test</Button>-->
            <Button type="primary" class="mr10" @click="save('form')">保存</Button>
          </div>
        </Col>
      </Row>
    </Form>
    <CImage ref="cImageRef" />
  </div>
</template>
<script>
import {
  addNotice, findNodes,
  getNotice, selectDictList,
  selectNoticeIdByAttachList,
  updateNotice,
  uploadFile
} from '@/api/contradiction.js'
import axios from 'axios'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import CImage from '_c/c-image/index.vue'

export default {
  name: 'noticeEdit',
  components: { CImage, Treeselect },
  data () {
    return {
      formInline: {
        userId: this.$store.state.user.severUserInfo.id,
        areaList: [],
        department: '0',
        sort: '2'
      },
      isReadOnly: this.$route.query.isReadOnly,
      imgArr: [],
      urlList: [],
      options: [],
      options2: [],
      treeParams: {
        id: '000000000000',
        type: '1',
        isAll: '0',
        isValue: '0'
      },
      valueFormat: 'object',
      suffixList: ['jpg', 'jpeg', 'png'],
      msg: null
    }
  },
  computed: {
    serverUserInfo () {
      return this.$store.state.user.severUserInfo
    }
  },
  watch: {},
  async created () {
    console.log(this.$route.query, 'this.$route.query')
    this.isReadOnly = this.$route.query.isReadOnly
    await this._findNodes()
    this.getDictList()
    if (this.$route.query.id) {
      this.getImg()
      this.getInfo()
    }
  },
  async activated () {
    console.log(this.$route.query, 'this.$route.query')
    this.isReadOnly = this.$route.query.isReadOnly
    await this._findNodes()
    this.getDictList()
    if (this.$route.query.id) {
      this.getImg()
      this.getInfo()
    }
  },
  deactivated () {
    this.formInline = {
      userId: this.$store.state.user.severUserInfo.id,
      areaList: [],
      department: '0'
    }
    this.isReadOnly = this.$route.query.isReadOnly
    this.imgArr = []
    this.urlList = []
    this.options = []
    this.options2 = []
    this.treeParams = {
      id: '000000000000',
      type: '1',
      isAll: '0',
      isValue: '0'
    }
  },
  // beforeDestroy() {
  //   this.formInline = {
  //     userId: this.$store.state.user.severUserInfo.id,
  //     areaList: [],
  //     department: '0',
  //   }
  //   this.isReadOnly = this.$route.query.isReadOnly
  //   this.imgArr = []
  //   this.urlList = []
  //   this.options = []
  //   this.options2 = []
  //   this.treeParams = {
  //     id: '000000000000',
  //     type: '1',
  //     isAll: '0',
  //     isValue: '0'
  //   }
  // },
  methods: {
    getDictList () {
      selectDictList({ type: 'notice_type', parent_id: 0 }).then(res => {
        this.options2 = res.data.data
      })
    },
    getImg () {
      this.imgArr = []
      selectNoticeIdByAttachList({ id: this.$route.query.id }).then((res) => {
        if (res.data.errcode === 0) {
          let imgList = res.data.data
          this.urlList = res.data.data
          imgList.forEach((element) => {
            // 把后台返回的uuid传给接口，同时传递完整的附件信息
            this.getImgUrl(element.uuid, element.suffix, element)
          })
          return
        }
        this.$Message.error(res.data.errmsg)
      })
    },
    getImgUrl (uuid, suffix, fileInfo) {
      let that = this
      axios({
        method: 'get',
        responseType: 'arraybuffer',
        url:
          '/api/ac/jilinsscgsdp/uploadService/getObsObject?uuid=' +
          uuid +
          '&&suffix=' +
          suffix
      }).then(function (res) {
        // 构建完整的附件对象，包含所有必要信息
        let fileObj = {
          uuid: fileInfo.uuid,
          suffix: suffix,
          originalFilename: fileInfo.original_name
        }
        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.imgArr.push(fileObj)
        // 调用下载方法，把后端传过来的流传给fileDownload方法
        // this.fileDownload(res.data, fileName)
      })
    },
    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 if (item.suffix === 'pdf') {
        // 关键步骤：ArrayBuffer 转 Blob（指定 MIME 类型为 PDF）
        const pdfBlob = new Blob([item.url], { type: 'application/pdf' })
        // 生成 Blob URL（无长度限制，浏览器原生支持）
        const blobUrl = URL.createObjectURL(pdfBlob)
        // 打开预览（window.open 直接用 Blob URL，不会被截断）
        window.open(blobUrl, '_blank') // _blank 新建标签页

        // 可选：页面卸载时释放 Blob URL（避免内存泄漏）
        window.addEventListener('unload', () => {
          URL.revokeObjectURL(blobUrl)
        })
      } else {
        window.open(item.url, '_blank')
      }
      console.log(item, index)
    },
    delFile (item, index) {
      this.urlList.splice(index, 1)
      this.imgArr.splice(index, 1)
      console.log(item, index)
    },
    // 上传图片前转base64
    beforeUpload (file) {
      // const allowedTypes = ['image/jpeg', 'image/png']
      // const isImage = allowedTypes.includes(file.type)
      // if (!isImage) {
      //   this.$Message.error('请上传图片格式')
      //   return
      // }
      // console.log(isImage, 'isImage')
      const fileType = file.name.split('.').pop()
      const fileTypes = [...this.suffixList, 'pdf']
      if (!fileTypes.includes(fileType)) {
        this.$Message.error({
          content: `请上传${fileTypes.join('、')}格式的文件`,
          duration: 5
        })
        return
      }
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        // 初始时先保存文件名，上传成功后再更新为服务器返回的文件名
        this.imgArr.push({
          url: e.target.result,
          originalFilename: file.name,
          suffix: file.name.split('.').pop()
        })
      }
      let formdata = new FormData()
      formdata.append('file', file)
      formdata.append('fileName', file.name)
      formdata.append('json', JSON.stringify({ business_type: 'jlEvent' }))
      console.log(formdata, 'dada adasdasdsad')
      this.msg = this.$Message.loading({
        content: 'Loading...',
        duration: 0
      })
      uploadFile(formdata).then((res) => {
        let len = this.imgArr.length
        // 使用 $set 确保 Vue 响应式更新
        this.$set(this.imgArr[len - 1], 'uuid', res.data.data.uuid)
        this.$set(this.imgArr[len - 1], 'suffix', res.data.data.suffix)
        this.$set(this.imgArr[len - 1], 'originalFilename', res.data.data.originalFilename)
        this.urlList.push(res.data.data)
        setTimeout(this.msg, 3000)
      })
      console.log(this.imgArr, 'this.imgArr')
    },
    save () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let url = this.$route.query.id ? updateNotice : addNotice
          this.formInline.urlList = this.urlList
          const data = JSON.parse(JSON.stringify(this.formInline))
          const isSheng = data.areaList.find(item => item._id === '220000000000')
          if (isSheng) {
            data.areaList = [isSheng]
          }
          const department = []
          data.areaList.forEach(item => {
            item.id = item._id
            delete item.children
            delete item.hasChildren
            delete item._id
            department.push(item.name)
          })
          data.department = department.join(',')
          data.sort = '2'
          url(data).then(res => {
            if (res.data.errcode === 0) {
              this.$Message.success('成功')
              this.$router.go(-1)
              return
            }
            this.$Message.error(res.data.errmsg)
          })
        }
      })
    },
    getInfo () {
      getNotice({ id: this.$route.query.id }).then(res => {
        if (res.data.errcode === 0) {
          let list = []
          if (res.data.data.areaList) {
            const areaList = JSON.parse(res.data.data.areaList)
            list = areaList.map(item => {
              return {
                id: item.id + '_' + item.isValue + '_' + item.isAll,
                _id: item.id,
                // 重要：设置hasChildren属性来指示节点是否有子节点
                hasChildren: !(item.isAll === '1' && item.isValue === '0'),
                // 初始时不加载children
                children: null,
                isAll: item.isAll,
                isValue: item.isValue,
                name: item.name,
                parentIds: item.parentIds,
                type: item.type
              }
            })
          }

          res.data.data.areaList = list
          this.formInline = res.data.data
          this.formInline.sort = res.data.data.sort + ''
          return
        }
        this.$Message.error(res.data.errmsg)
      })
    },
    normalizer (node) {
      const normalizedNode = {
        id: node.id,
        label: node.name,
        hasChildren: node.isAll === '0',
        children: null,
        ...node
      }

      return normalizedNode
    },
    async _findNodes () {
      try {
        // 判断当前登录人的 company_grade 是否为 '3'市  '4'区
        const userInfo = this.$store.state.user.severUserInfo
        if (userInfo && (userInfo.company_grade === '3' || userInfo.company_grade === '4')) {
          const type = userInfo.company_grade === '3' ? '2' : '3'
          const rootNode = {
            id: userInfo.company_id + '_0_0',
            _id: userInfo.company_id,
            name: userInfo.company_name,
            hasChildren: true,
            children: null,
            isAll: '0',
            isValue: '0',
            type: type
          }
          this.options = [rootNode]
          return
        }

        // 正常调用 API 加载数据
        const res = await findNodes(this.treeParams)
        if (res.data.errcode === 0) {
          const processedData = res.data.data.map(item => {
            return {
              ...item,
              id: item.id + '_' + item.isValue + '_' + item.isAll,
              _id: item.id,
              // 重要：设置hasChildren属性来指示节点是否有子节点
              hasChildren: item.isAll === '0',
              // 初始时不加载children
              children: null
            }
          })

          this.options = processedData
          console.log('Processed options:', this.options)
        } else {
          console.error('Error loading nodes:', res.data.errmsg)
          this.$Message.error('加载部门数据失败')
        }
      } catch (error) {
        console.error('Error in _findNodes:', error)
        this.$Message.error('加载部门数据时发生错误')
      }
    },
    async loadOptions ({ action, parentNode, callback }) {
      console.log('参数>loadOptions>', action, parentNode)

      try {
        if (parentNode.isAll === '1' && parentNode.isValue === '0') {
          return callback()
        }
        const originalId = parentNode.id.split('_')[0]

        // 构建正确的请求参数
        const requestParams = { ...parentNode, type: Number(parentNode.type) + 1, id: originalId }

        console.log('Request params:', requestParams)

        const res = await findNodes(requestParams)

        if (res.data.errcode === 0) {
          const processedChildren = res.data.data.map(item => {
            return {
              ...item,
              id: item.id + '_' + item.isValue + '_' + item.isAll,
              _id: item.id,
              // 重要：设置hasChildren属性来指示节点是否有子节点
              hasChildren: !(item.isAll === '1' && item.isValue === '0'),
              // 初始时不加载children
              children: null
            }
          })

          console.log('res>loadOptions>>', processedChildren)

          // 设置父节点的children
          parentNode.children = processedChildren
          console.log('parentNode after setting children>>', parentNode)

          // 调用callback通知treeselect数据已加载
          callback()
        } else {
          console.error('Error loading children:', res.data.errmsg)
          this.$Message.error('加载子部门数据失败')
          callback(new Error(res.data.errmsg))
        }
      } catch (error) {
        console.error('Error in loadOptions:', error)
        this.$Message.error('加载子部门数据时发生错误')
        callback(error)
      }
    },
    handleSelect (v) {
      // 他山之石
      if (v === '694f210d-b4a5-11f0-8e0b-fa163eb6e42a' || v === 'd24f9701-c6c3-11f0-887f-fa163e4d9c13') {
        console.log('他山之石')
        this.formInline.areaList = []
        this.formInline.areaList.push(this.options[0])
        // console.log('this.areaList>>', this.formInline.areaList)
      }
    }
  }
}
</script>

<style scoped lang="less">
.contradiction-div {
  // padding: 10px;
  background: #fff;
  padding:10px;
  font-size: 14px;
  .title-style {
    padding: 8px 12px;
    background-color: #ecf8ff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 15px 0;
    font-size: 16px;
    width: 100%;
  }
  .more-style {
    background-color: #ecf8ff;
    width: 70px;
    padding: 8px 12px;
    border-radius: 4px;
  }
}
.ql-editor{
  width: 100%;
  max-height: 500px;
  min-height: 50px;
  overflow-y: auto;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  background-color: #f3f3f3;
  padding: 4px 7px;
}
.hover-effect {
  cursor: pointer; /* 小手效果 */
  transition: all 0.3s ease; /* 添加过渡效果使变化更平滑 */
}

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