<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-radio-group v-model="selectFromModel" size="medium">
                <el-radio-button label="选择模版"></el-radio-button>
                <el-radio-button label="新建任务"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="selectFromModel === '选择模版'">
          <el-row>
            <el-form-item label="视频巡查模版">
              <el-input
                v-model="templateName"
                @change="getTemplateData"
                clearable
                style="width: 300px; margin-bottom: 10px"
                placeholder="请输入模版名称"
              ></el-input>
              <el-table
                stripe
                row-key="id"
                class="table-list tamplate-table"
                ref="multipleSelection"
                :height="tableMaxHeight"
                :data="templateData"
                highlight-current-row
                @current-change="handleCurrentChange"
              >
                <el-table-column
                  align="center"
                  label="序号"
                  type="index"
                  width="120"
                />
                <el-table-column
                  align="center"
                  label="模版名称"
                  prop="confName"
                  show-overflow-tooltip
                />
                <el-table-column
                  :formatter="({roadName}) => roadName || '-'"
                  align="center"
                  label="所属区域"
                  min-width="70"
                  prop="roadName"
                  show-overflow-tooltip
                />
                <el-table-column
                  :formatter="
                    ({type}) =>
                      dictionaryEscape('xjlx-xjrw', type, {
                        congruent: false,
                      }) || '-'
                  "
                  align="center"
                  label="巡检类型"
                  min-width="70"
                  prop="type"
                  show-overflow-tooltip
                />
              </el-table>
              <pagination
                ref="paginationPanel"
                :pageResult="params.pageBean"
                style="margin-top: 10px"
                @size-change="handleSizeChange"
                @current-change="handleCurrentPageChange"
              />
            </el-form-item>
          </el-row>
        </template>
        <template v-if="selectFromModel === '新建任务'">
          <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="8">
              <el-form-item label="巡检视频点位" prop="taskConfVideo">
                <el-button
                  type="primary"
                  size="mini"
                  @click="showDialog('video')"
                  >+ &nbsp;视频点位</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  :disabled="!currentDataDel.length"
                  v-show="addEditForm.taskConfVideo.length"
                  @click="deleteVideo()"
                  >- &nbsp;视频点位</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row v-show="addEditForm.taskConfVideo.length">
          <el-table
            stripe
            row-key="id"
            class="table-list"
            ref="multipleSelection"
            :height="tableMaxHeight"
            :data="addEditForm.taskConfVideo"
            @selection-change="handleSelectionChange"
            v-show="addEditForm.taskConfVideo.length"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              align="center"
              label="序号"
              type="index"
              width="120"
            />
            <el-table-column
              align="center"
              label="视频点名称"
              prop="videoName"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="视频点编码"
              prop="videoId"
              show-overflow-tooltip
            />
            <!-- <el-table-column
                    align="center"
                    label="排序号"
                    prop="rank"
                    width="200"
                    show-overflow-tooltip
                    class-name="is-required"
                >
                    <template v-slot="{row, $index}">
                        <el-form-item
                            :prop="`taskConfVideo.${$index}.rank`"
                            :rules="addEditRules.rank"
                            class="table-form-item"
                        >
                            <el-input
                                size="small"
                                v-model.number="row.rank"
                                placeholder="请输入排序号"
                                type="number"
                            ></el-input>
                        </el-form-item>
                    </template>
                </el-table-column> -->
            <el-table-column
              show-overflow-tooltip
              width="200"
              align="center"
              label="操作"
            >
              <template v-slot="{$index}">
                <el-link
                  type="danger"
                  :underline="false"
                  @click="deleteVideo($index)"
                >
                  删除
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </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'

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()
        }
      },
    },
  },
  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()
    },

    // 改变页面
    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>
