<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-col :span="6">
            <el-form-item label="模版编码" prop="confCode">
              <el-input
                v-model="addEditForm.confCode"
                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>
        <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 {getDictionaryByCode} from '@/utils/dictionary'
import VideoSiteSelectorDialog from '@/components/TreeTableSelector/VideoSiteSelectorDialog/index.vue'
import moment from 'moment'

export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String,
    },
  },
  components: {
    VideoSiteSelectorDialog,
  },
  data() {
    return {
      tableMaxHeight: 460,
      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: [],
    }
  },
  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.addEditForm.roadId = data.roadId || ''
        this.addEditForm.roadName = data.roadName || ''
      }
    })
  },
  methods: {
    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.$refs.addEditForm.$el.scrollTop = 0
          this.$refs.addEditForm.clearValidate()
        })
      }, 0)
    },

    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'
      }
    },

    // 保存
    handleSave() {
      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) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`视频巡查模版${message}成功`)
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

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