<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form
        class="edit-add-form"
        ref="addEditForm"
        :model="addEditForm"
        :rules="addEditRules"
        label-width="100px"
        label-position="top"
        label-suffix="："
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">视频巡查任务</div>
          </div>
        </div>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="所属区域" prop="roadName">
              <el-input
                v-model="addEditForm.roadName"
                placeholder="所属区域"
                style="width: 100%"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="任务名称" prop="confName">
              <el-input
                v-model="addEditForm.confName"
                placeholder="请输入任务名称"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="巡检类型" prop="type">
              <el-select
                v-model="addEditForm.type"
                placeholder="请选择巡检类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in getDictionaryByCode('xjlx-xjrw')"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="附件" prop="policyFiles">
              <el-upload
                :data="{
                  file: JSON.stringify({storeType: 'minio'}),
                }"
                name="files"
                :action="actionUrl + '/file/v1/fileUpload'"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="handleError"
                :on-preview="handlePreview"
                :before-remove="beforeRemove"
                :on-remove="handleRemove"
                :multiple="true"
                :headers="headers"
                :file-list="addEditForm.policyFilesArr"
                ref="upload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="footer" slot="footer">
      <el-button type="primary" @click="handleSave" :loading="saveLoading">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('TablePage', id ? 'add' : 'edit')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>

    <!--  视频点位弹层  -->
    <VideoSiteSelectorDialog
      :is-show.sync="videoDialog"
      :selected-content.sync="addEditForm.taskConfVideo"
      @confirm="handleVideoConfirm"
    />

    <el-backtop target=".edit-add-form" :visibility-height="10">
      <div class="top-box">UP</div>
    </el-backtop>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {
  taskDetail,
  taskSave,
} from '@/api/patrolAndRescue/videoPatrol/videoConfig'
import pagination from '@/components/SuperPagination/index.vue'
import {getDictionaryByCode, dictionaryEscape} from '@/utils/dictionary'
import VideoSiteSelectorDialog from '@/components/TreeTableSelector/VideoSiteSelectorDialog/index.vue'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue,
} from '@/utils/requestWrappers'
import {
  tableData,
  executeJob,
} from '@/api/patrolAndRescue/videoPatrol/videoConfig'
import {mapState} from 'vuex'
export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String,
    },
  },
  components: {
    VideoSiteSelectorDialog,
    pagination,
  },
  data() {
    return {
      tableMaxHeight: 460,
      selectFromModel: '选择模版',
      addEditForm: {
        confName: '',
        confCode: '',
        type: '',
        roadId: '',
        roadName: '',
        confType: '',
        taskConfVideo: [],
      },
      addEditRules: {
        confName: [
          {
            required: true,
            message: '模版名称不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        confCode: [
          {
            required: true,
            message: '模版编码不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        type: [
          {
            required: true,
            message: '巡检类型不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        taskConfVideo: [
          {
            required: true,
            message: '巡检视频点位不能为空',
            trigger: 'change',
          },
        ],
        rank: [
          {
            required: true,
            message: '排序号不能为空',
            trigger: 'blur',
          },
        ],
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      saved: false, // 新增成功
      whetherToCancel: false,
      pubSub: null,
      videoDialog: false,
      planDisable: false,
      currentDataDel: [],
      templateData: [], // 巡检模版数据
      templateName: [],
      currentRow: {},
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'confName'},
          {operation: 'EQUAL', property: 'roadId'},
        ],
        sorter: [{direction: '', property: ''}],
      },
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      },
    },
  },
  computed: {
    actionUrl: (_) => window.context.portal,
    previewUrl: (_) =>
      window.context.portal + '/file/onlinePreviewController/v1/getFileById_',
    downloadUrl: (_) => window.context.portal + '/file/v1/downloadFile?fileId=',
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
  },
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        this.currentRow = {}
        this.addEditForm.roadId = data.roadId || ''
        this.addEditForm.roadName = data.roadName || ''
        setQueryValue(this.params, 'roadId', data.roadId || '')
        this.loadTemplateData()
      }
    })
  },
  methods: {
    dictionaryEscape,
    getDictionaryByCode,
    // 打开页面执行
    openPage() {
      this.whetherToCancel = true
    },

    // 关闭页面执行
    closePage() {
      const {addEditRules, pubSub} = this
      this.$refs.uploader?.uploader?.cancel()

      setTimeout((_) => {
        Object.assign(this.$data, this.$options.data.call(this), {
          addEditRules,
          pubSub,
        })
        // 重置组件数据
        this.$nextTick((_) => {
          this.currentRow = {}
          this.$refs.addEditForm.$el.scrollTop = 0
          this.$refs.addEditForm.clearValidate()
        })
      }, 0)
    },

    async loadTemplateData() {
      try {
        this.tableLoading = true
        const {total = 0, rows = []} = await tableData(
          refineRequestBody(this.params)
        )
        this.params.pageBean.total = total
        this.templateData = rows.map((i) => ({
          isEnable: i.taskStatus === 'NORMAL',
          ...i,
        }))
      } finally {
        this.tableLoading = false
      }
    },

    getTemplateData(val) {
      setQueryValue(this.params, 'confName', val || '')
      this.loadTemplateData()
    },

    handleSelectionChange(val) {
      this.currentDataDel = val.map((item) => item.id)
    },

    handleVideoConfirm(data) {
      const tempData = data.map((item, index) => {
        item.rank = index // item.rank ? item.rank : index + 1
        item.videoId = item.id
        item.videoName = item.name
        return item
      })

      this.$set(this.addEditForm, 'taskConfVideo', tempData)
      this.addEditForm.taskConfVideo = tempData
      this.$forceUpdate()
    },

    deleteVideo(index) {
      this.$confirm('确定删除选中视频点位吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          if (index || index === 0) {
            this.addEditForm.taskConfVideo.splice(index, 1)
          } else {
            let tempData = this.addEditForm.taskConfVideo.filter(
              (item) => !this.currentDataDel.includes(item.id)
            )

            console.log(tempData, this.addEditForm.taskConfVideo)
            this.addEditForm.taskConfVideo = [...tempData]
          }
        })
        .catch((_) => _)
    },

    showDialog(type) {
      this[`${type}Dialog`] = true
    },

    // 获取详情
    async getDetail(id) {
      const {
        planType = '',
        taskConfVideo = [],
        confType = '',
        type = '',
        ...addEditForm
      } = await taskDetail(id)

      let taskConfVideoTamp = taskConfVideo.sort((a, b) => {
        return a.rank - b.rank
      })

      this.addEditForm = {
        confType: confType.toString() || '',
        planType: planType.toString() || '',
        type: type.toString() || '',
        taskConfVideo: taskConfVideoTamp.map((item) => {
          item.id = item.videoId
          item.rank = item.rank
          item.name = item.videoName
          return item
        }),
        ...addEditForm,
      }
    },

    // 模版类型改变
    changeConfType(val) {
      if (val === '2') {
        this.planDisable = true
        this.addEditForm.planType = '1'
      } else {
        this.planDisable = false
        this.addEditForm.planType = '1'
      }
    },
    // 选择模版
    handleCurrentChange(val) {
      this.currentRow = val
    },
    // 保存
    async handleSave() {
      if (this.selectFromModel === '选择模版') {
        if (!this.currentRow.id) {
          this.$message.warning('请选择模版')
          return
        }
        let data = this.qs.stringify({
          id: this.currentRow.id,
        })
        const {state, message} = await executeJob(data)
        if (state) {
          this.$message.success(`视频巡检任务添加成功`)
          this.changePage('TablePage', this.id ? 'edit' : 'add')
        } else {
          this.$message.warning(message || `视频巡检任务添加失败！`)
        }
      } else {
        this.$refs.addEditForm.validate(async (valid, object) => {
          if (!valid) {
            this.$message.warning(
              `有${
                Object.keys(object).length
              }个字段未通过校验，请正确填写表单内容。`
            )
          } else {
            this.saveLoading = true
            const {taskConfVideo = [], ...addEditForm} = this.addEditForm

            try {
              let {state, message, value} = await taskSave({
                taskConfVideo: taskConfVideo.map((item) => {
                  const {rank, taskConfId = '', videoId, videoName} = item
                  return {
                    rank,
                    taskConfId,
                    videoId,
                    videoName,
                  }
                }),
                ...addEditForm,
              })
              if (state) {
                this.changePage('TablePage', this.id ? 'edit' : 'add')
                let data = this.qs.stringify({
                  id: value,
                })
                const {state, message} = await executeJob(data)
                if (state) {
                  this.$message.success(`视频巡检任务添加成功`)
                  this.changePage('TablePage', this.id ? 'edit' : 'add')
                } else {
                  this.$message.warning(message || `视频巡检任务添加失败！`)
                }
              } else {
                this.$message.warning(message || `视频巡检任务添加失败！`)
              }
            } finally {
              this.saveLoading = false
            }
          }
        })
      }
    },

    //分页页数切换
    handleCurrentPageChange(page = 1) {
      if (!this.params?.pageBean?.page) return
      this.params.pageBean.page = page
      this.loadTemplateData()
    },

    //分页大小切换
    handleSizeChange(pageSize = 10) {
      if (!this.params?.pageBean?.page) return
      this.params.pageBean.pageSize = pageSize
      this.loadTemplateData()
    },

    // 文件上传前
    beforeUpload(file) {
      // this.saveLoading = true
      // const {size} = file
      // const maxSize = 20 * 1024 * 1024 // 20MB
      // if (size > maxSize) {
      //     this.$message.warning('附件大小不能超过20MB')
      //     setTimeout((_) => (this.saveLoading = false), 0)
      //     return false
      // }
    },

    // 文化上传成功
    handleSuccess(response) {
      const {
        fileId = '',
        fileName = '',
        size: fileSizes = 0,
        success,
      } = response
      if (success) {
        this.addEditForm.policyFiles.push({fileId, fileSizes, fileName})
      } else {
        this.$message.error('文件上传失败')
      }
      this.saveLoading = false
    },

    // 文件上传失败
    handleError() {
      this.$message.warning('文件上传失败')
    },

    // 文件删除前
    beforeRemove(file) {
      return new Promise((resolve, reject) => {
        this.$confirm(`确定移除${file.name}吗？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then((_) => {
            resolve()
          })
          .catch((_) => reject())
      })
    },

    // 文件删除后
    handleRemove(file) {
      const fileId = file.fileId || file.response.fileId || ''
      const index = this.addEditForm.policyFiles.findIndex(
        (i) => i.fileId === fileId
      )
      if (index !== -1) this.addEditForm.policyFiles.splice(index, 1)
    },

    // 已上传文件点击
    async handlePreview(file) {
      const fileId = file.fileId || file.response.fileId || '' // 文件ID
      const fileName = file.name || file.fileName || '' // 文件名
      if (!(fileId && fileName))
        return this.$message.warning('文件错误，请删除后重新上传')
      const browserOperablePattern = /\.(jpg|jpeg|png|gif|bmp|webp|pdf)$/i
      if (browserOperablePattern.test(fileName)) {
        window.open(this.previewUrl + fileId, '_blank')
      } else {
        window.open(this.downloadUrl + fileId, '_blank')
      }
    },

    // 改变页面
    changePage(pageName = '', type = '', data = {}) {
      if (!pageName) return
      this.$emit('changePage', pageName, (_) => {
        PubSub.publish(pageName, {type, ...data})
      })
    },
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  },
}
</script>

<style lang="scss" scoped>
.flex{
    display: flex;
}
.tag-box{
    margin-bottom: 10px;
}

::v-deep .tamplate-table .el-table__row.current-row .el-table__cell {
    background-color: #195f97!important;
    color: #d8e2eb!important;
}
</style>
