<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form
        :class="['edit-add-form', {edit: id}]"
        ref="addEditForm"
        :model="addEditForm"
        :rules="addEditRules"
        label-width="120px"
        :label-position="id ? 'left' : '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="8">
            <el-form-item label="所属区域" prop="regionName">
              <el-input
                v-model="addEditForm.regionName"
                placeholder="所属区域"
                style="width: 100%"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="id">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="路段名称"
                prop="roadName"
                class="table-form-item"
              >
                <el-input
                  v-model="addEditForm.roadName"
                  placeholder="请输入路段名称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="检查类型"
                prop="checkType"
                class="table-form-item"
              >
                <el-select
                  v-model="addEditForm.checkType"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('spxj-jclx')"
                    :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="inspectionType"
                class="table-form-item"
              >
                <el-select
                  v-model="addEditForm.inspectionType"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('spxj-xjlx')"
                    :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="placeName"
                class="table-form-item"
              >
                <el-input
                  v-model="addEditForm.placeName"
                  placeholder="请输入检查地点"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="巡检日期"
                prop="inspectionDate"
                class="table-form-item"
              >
                <el-date-picker
                  v-model="addEditForm.inspectionDate"
                  value-format="yyyy-MM-dd"
                  align="right"
                  type="date"
                  placeholder="请选择"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="巡检时间"
                prop="inspectionTime"
                class="table-form-item"
              >
                <el-time-picker
                  v-model="addEditForm.inspectionTime"
                  placeholder="请选择"
                  value-format="HH:mm:ss"
                >
                </el-time-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="巡检结果"
                prop="inspectionResult"
                class="table-form-item"
              >
                <el-select
                  v-model="addEditForm.inspectionResult"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in getDictionaryByCode('spxj-xjjg')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                    <i
                      class="el-icon-close"
                      style="color: #f56c6c; margin-right: 2px"
                      v-if="item.value === '2'"
                    ></i>
                    <i
                      class="el-icon-check"
                      style="color: #67c23a; margin-right: 2px"
                      v-if="item.value === '1'"
                    ></i>
                    <span>{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                label="记录人"
                prop="recordUser"
                class="table-form-item"
              >
                <el-input
                  v-model="addEditForm.recordUser"
                  placeholder="请输入记录人"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="异常处理记录"
                prop="resultRecord"
                class="table-form-item"
              >
                <el-input
                  type="textarea"
                  v-model="addEditForm.resultRecord"
                  placeholder="请输入异常处理记录"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="备注" prop="remark" class="table-form-item">
                <el-input
                  type="textarea"
                  v-model="addEditForm.remark"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row class="left" :gutter="24" v-if="!id">
          <el-col :span="8">
            <el-form-item label="巡检记录" prop="taskConfVideo">
              <el-popover
                v-model="isShowPopover"
                :width="popoverWidth"
                placement="bottom-start"
                popper-class="import-popover"
                trigger="click"
              >
                <div class="popover-container">
                  <div class="popover-container-title">
                    <div class="popover-container-title-left">
                      <i class="el-icon-warning" /> 提示：
                    </div>
                    <div
                      class="popover-container-title-right"
                      @click="isShowPopover = false"
                    >
                      <i class="el-icon-close" />
                    </div>
                  </div>
                  <div class="popover-container-content">
                    请下载巡检记录模板并完成模板文件的录入后，导入已录入信息的模板文件。
                  </div>
                  <div class="popover-container-btn">
                    <el-button
                      :loading="downloadLoading"
                      class="btn btn-plus"
                      icon="el-icon-download"
                      plain
                      size="mini"
                      type="primary"
                      @click="downloadTemplate"
                    >
                      下载模版
                    </el-button>

                    <el-upload
                      ref="upload"
                      :action="action"
                      :before-upload="beforeUpload"
                      :headers="headers"
                      :multiple="false"
                      :on-error="handleError"
                      :on-success="handleSuccess"
                      :show-file-list="false"
                    >
                      <el-button
                        :loading="uploadLoading"
                        class="btn btn-plus"
                        icon="el-icon-upload2"
                        plain
                        size="mini"
                        type="warning"
                      >
                        导入模版
                      </el-button>
                    </el-upload>
                  </div>
                </div>
                <template v-slot:reference>
                  <el-button
                    class="btn btn-plus"
                    icon="el-icon-upload"
                    style="margin: 0 10px"
                    type="warning"
                    size="mini"
                  >
                    导入记录
                  </el-button>
                </template>
              </el-popover>
              <el-button type="primary" size="mini" @click="addVideo"
                >+ &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 class="left" v-show="!id && 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="60"
            />
            <el-table-column
              align="center"
              label="路段名称"
              prop="roadName"
              width="160"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.roadName`"
                  :rules="addEditRules.roadName"
                  class="table-form-item"
                >
                  <el-input
                    v-model="row.roadName"
                    placeholder="请输入路段名称"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="检查类型"
              prop="checkType"
              width="140"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.checkType`"
                  :rules="addEditRules.checkType"
                  class="table-form-item"
                >
                  <el-select
                    v-model="row.checkType"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in getDictionaryByCode('spxj-jclx')"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="巡检类型"
              prop="inspectionType"
              width="140"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.inspectionType`"
                  :rules="addEditRules.inspectionType"
                  class="table-form-item"
                >
                  <el-select
                    v-model="row.inspectionType"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in getDictionaryByCode('spxj-xjlx')"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="检查地点"
              prop="placeName"
              min-width="200"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.placeName`"
                  :rules="addEditRules.placeName"
                  class="table-form-item"
                >
                  <el-input
                    v-model="row.placeName"
                    placeholder="请输入检查地点"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="巡检日期"
              prop="inspectionDate"
              min-width="160"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.inspectionDate`"
                  :rules="addEditRules.inspectionDate"
                  class="table-form-item"
                >
                  <el-date-picker
                    v-model="row.inspectionDate"
                    value-format="yyyy-MM-dd"
                    align="right"
                    type="date"
                    placeholder="请选择"
                  >
                  </el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="巡检时间"
              prop="inspectionTime"
              min-width="140"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.inspectionTime`"
                  :rules="addEditRules.inspectionTime"
                  class="table-form-item"
                >
                  <el-time-picker
                    v-model="row.inspectionTime"
                    placeholder="请选择"
                    value-format="HH:mm:ss"
                  >
                  </el-time-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="巡检结果"
              prop="inspectionResult"
              width="120"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.inspectionResult`"
                  :rules="addEditRules.inspectionResult"
                  class="table-form-item"
                >
                  <el-select
                    v-model="row.inspectionResult"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in getDictionaryByCode('spxj-xjjg')"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    >
                      <i
                        class="el-icon-close"
                        style="color: #f56c6c; margin-right: 2px"
                        v-if="item.value === '2'"
                      ></i>
                      <i
                        class="el-icon-check"
                        style="color: #67c23a; margin-right: 2px"
                        v-if="item.value === '1'"
                      ></i>
                      <span>{{ item.name }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="记录人"
              prop="recordUser"
              width="140"
              show-overflow-tooltip
              class-name="is-required"
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.recordUser`"
                  :rules="addEditRules.recordUser"
                  class="table-form-item"
                >
                  <el-input
                    v-model="row.recordUser"
                    placeholder="请输入记录人"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="异常处理记录"
              prop="resultRecord"
              min-width="200"
              show-overflow-tooltip
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.resultRecord`"
                  class="table-form-item"
                >
                  <el-input
                    v-model="row.resultRecord"
                    placeholder="请输入异常处理记录"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="备注"
              prop="remark"
              min-width="200"
              show-overflow-tooltip
            >
              <template v-slot="{row, $index}">
                <el-form-item
                  :prop="`taskConfVideo.${$index}.remark`"
                  class="table-form-item"
                >
                  <el-input
                    v-model="row.remark"
                    placeholder="请输入备注"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
          <!-- <pagination
            ref="paginationPanel"
            :pageResult="pageResult"
            style="margin-top: 10px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />-->
        </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>

    <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 {mapState} from 'vuex'
import {
  taskSave,
  taskDetail,
  taskUpdate,
  downloadModel,
} from '@/api/patrolAndRescue/videoPatrol/videoPatrolRecord'
import {getDictionaryByCode} from '@/utils/dictionary'
import pagination from '@/components/SuperPagination/index.vue'
import moment from 'moment'
import utils from '@/utils/utils'
import {calcFontSize} from '@/utils/responsiveUtils'
export default {
  name: 'EditAddPage',
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String,
    },
  },
  components: {
    pagination,
  },
  data() {
    return {
      tableMaxHeight: 550,
      addEditForm: {
        regionId: '',
        regionName: '',
        taskConfVideo: [],
      },
      addEditRules: {
        roadName: [
          {
            required: true,
            message: '路段名称不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        checkType: [
          {
            required: true,
            message: '检查类型不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        inspectionType: [
          {
            required: true,
            message: '巡检类型不能为空',
            trigger: ['blur', 'change'],
          },
        ],
        placeName: [
          {
            required: true,
            message: '检查地点不能为空',
            trigger: 'change',
          },
        ],
        inspectionDate: [
          {
            required: true,
            message: '巡检日期不能为空',
            trigger: 'blur',
          },
        ],
        inspectionTime: [
          {
            required: true,
            message: '巡检时间不能为空',
            trigger: 'blur',
          },
        ],
        inspectionResult: [
          {
            required: true,
            message: '巡检结果不能为空',
            trigger: 'blur',
          },
        ],
        recordUser: [
          {
            required: true,
            message: '记录人不能为空',
            trigger: 'blur',
          },
        ],
      },
      pageResult: {
        size: 1,
        pageSizes: 20,
        total: 0,
      },
      saveLoading: false, // 上传loading
      id: '', // id标识符
      saved: false, // 新增成功
      whetherToCancel: false,
      pubSub: null,
      planDisable: false,
      currentDataDel: [],
      isShowPopover: false, // 是否展示Popover
      uploadLoading: false, // 上传loading
      downloadLoading: false, // 下载模版loading
      popoverWidth: calcFontSize(360),
    }
  },
  computed: {
    actionUrl: (_) => window.context.portal,
    action() {
      return `${this.actionUrl}/bizVideoInspection/v1/import`
    },
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
  },
  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.regionId = data.regionId || ''
        this.addEditForm.regionName = data.regionName || ''
      }
    })
  },
  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)
    },

    handleSizeChange(val) {
      this.pageResult.size = val
      this.getDetail(this.id)
    },

    handleCurrentChange(val) {
      this.pageResult.page = val
      this.getDetail(this.id)
    },

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

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

    addVideo() {
      const newVideo = {
        key: utils.uuid(),
        roadName: '',
        checkType: '1',
        inspectionType: '1',
        placeName: '',
        inspectionDate: moment().format('YYYY-MM-DD'),
        inspectionTime: moment().format('HH:mm:ss'),
        inspectionResult: '1',
        recordUser: '',
        resultRecord: '',
        remark: '',
      }
      this.addEditForm.taskConfVideo.splice(0, 0, newVideo)
      this.pageResult.total = this.addEditForm.taskConfVideo.length
    },

    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.key)
            )

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

    // 获取详情
    async getDetail(id) {
      const {regionId, regionName, ...rest} = await taskDetail(id)

      this.addEditForm = {
        regionId,
        regionName,
        ...rest,
        taskConfVideo: [],
      }
    },

    // 模版类型改变
    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 = [],
            regionId,
            regionName,
            ...rest
          } = this.addEditForm

          let queryData, API
          if (this.id) {
            queryData = {
              regionId,
              regionName,
              ...rest,
            }
            API = taskUpdate
          } else {
            queryData = taskConfVideo.map((item) => {
              const {key, ...rest} = item
              return {
                regionId,
                regionName,
                ...rest,
              }
            })
            API = taskSave
          }

          try {
            let {state, message, value} = await API(queryData)
            if (state) {
              message = this.id ? '编辑' : '新增'
              this.$message.success(`视频巡查模版${message}成功`)
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 下载导入模版
    downloadTemplate() {
      this.downloadLoading = true
      downloadModel()
        .then((_) => this.$message.success('下载视频巡检记录模板成功'))
        .finally((_) => {
          this.downloadLoading = false
          this.isShowPopover = false
        })
    },

    // 文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true
        const {size, name} = file
        this.$confirm(`请确认是否导入 “${name}” ？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then((_) => {
            let passedOrNot = true // 是否通过验证
            const maxSize = 500 * 1024 * 1024 // 20MB
            const typeRegular = /\.(xls|xlsx)$/i
            const verification = [
              {
                condition: !typeRegular.test(name),
                result: () => this.$message.error('只能上传xls或xlsx文件类型'),
              },
            ]
            verification.forEach((item) => {
              if (item.condition) {
                item.result()
                passedOrNot = false
                this.uploadLoading = false
              }
            })
            passedOrNot ? resolve() : reject()
            this.isShowPopover = passedOrNot
          })
          .catch((_) => {
            reject()
            this.isShowPopover = true
            this.uploadLoading = false
            this.$message.warning('已取消巡检记录上传')
          })
      })
    },

    // 文化上传成功
    handleSuccess(response) {
      const {value = []} = response
      this.topicDialog = false
      this.$message.success('巡检记录导入成功')
      this.uploadLoading = false
      this.addEditForm.taskConfVideo = value
      this.pageResult.total = value.length
      this.pageResult.size = 1
      this.isShowPopover = false
    },

    // 文件上传失败
    handleError() {
      this.$message.error('巡检记录导入失败，请重试')
      this.uploadLoading = false
      this.isShowPopover = 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;
}
::v-deep .edit-add-form.edit{
    .el-row{
        margin-left: 80px!important;
    }
} 

</style>
