<template>
  <el-card shadow="hover">
    <template #header>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete()"> 删除 </el-button>
        </el-col>
      </el-row>
    </template>

    <el-table
      v-loading="loading"
      :default-sort="{ prop: 'startTime,endTime', order: 'descending' }"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="演练名称" align="center" prop="drillName" />
      <el-table-column label="演练单位" align="center" prop="drillUnit" />
      <el-table-column label="年度" align="center" prop="year" :show-overflow-tooltip="true" />
      <el-table-column label="演练时间" align="center" prop="drillTime" width="160">
        <template #default="scope">
          <span>{{ scope.row.year }}</span>
        </template>
      </el-table-column>
      <el-table-column label="演练地点" align="center" prop="drillAddress" />
      <el-table-column label="演练方案" align="center" prop="drillProject">
        <template #default="scope">
          <a :href="baseUrl + downLoadApi + scope.row.drillProject[0].url" target="_blank">
            <el-text type="primary">{{
              scope.row && scope.row.drillProject && scope.row.drillProject[0] ? scope.row.drillProject[0].name : ''
            }}</el-text>
          </a>
        </template>
      </el-table-column>
      <el-table-column label="演练视频" align="center" prop="drillVideo">
        <template #default="scope">
          <el-text type="primary" @click="handleShowVideo(scope.row.drillVideo)">查看</el-text>
        </template>
      </el-table-column>
      <el-table-column label="演练图片" align="center" prop="drillPicture">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.url"
            :preview-src-list="scope.row.urlList"
            :preview-teleported="true"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-text v-hasPermi="['system:menu:Edit']" class="common-btn-text-primary" @click="handleUpdate(scope.row)">编辑</el-text>
          <el-text v-hasPermi="['system:menu:Download']" class="common-btn-text-primary" @click="handleDownload(scope.row)">下载</el-text>
          <el-text v-hasPermi="['system:menu:Delete']" class="common-btn-text-danger" @click="handleDelete(scope.row)">删除</el-text>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > queryParams.pageSize"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.pageSize"
      :total="total"
      @pagination="getList"
    />
  </el-card>
  <!-- 添加或修改演练记录配置对话框 -->
  <el-dialog ref="formDialogRef" v-model="visible" :title="title" width="500px" append-to-body @close="closeDialog">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="演练名称：" prop="drillName">
        <el-input v-model="form.drillName" placeholder="请输入演练名称" />
      </el-form-item>
      <el-form-item label="演练单位：" prop="drillUnit">
        <el-input v-model="form.drillUnit" placeholder="请输入演练单位" />
      </el-form-item>
      <el-form-item label="年度：" prop="year">
        <el-input v-model="form.year" placeholder="请输入演练年度" />
      </el-form-item>
      <el-form-item label="演练时间：" prop="drillTime">
        <el-date-picker
          v-model="form.drillTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择开始时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="演练地点：" prop="drillAddress">
        <el-input v-model="form.drillAddress" placeholder="请选择演练地点" readonly>
          <template #append>
            <div style="cursor: pointer" @click="openMapDialog">地图定位</div>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="演练方案：" prop="drillProject">
        <FileUpload v-model="form.drillProject" :file-type="['pdf', 'xls', 'xlsx', 'doc', 'docx']" :limit="1" />
      </el-form-item>
      <el-form-item label="演练视频：" prop="drillVideo">
        <FileUpload v-model="form.drillVideo" :file-type="['mp4', 'avi', 'wmv']" :limit="3" :file-size="5 * 1024" />
      </el-form-item>
      <el-form-item label="演练图片：" prop="drillPicture">
        <FileUpload v-model="form.drillPicture" :file-type="['jpg', 'jpeg', 'png']" :limit="12" :file-size="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <!--视频弹窗-->
  <el-dialog v-model="showVideo" title="视频详情" width="500px" append-to-body>
    <div v-for="(item, index) in videoList" :key="index" class="video-box">
      <div style="font-weight: bold; font-size: 18px; margin-bottom: 10px">{{ item.name }}</div>
      <video :src="baseUrl + downLoadApi + item.url" controls width="100%" height="100%"></video>
    </div>
  </el-dialog>
  <!-- 地图弹窗 -->
  <company-map v-model:visible="mapDialogVisible" :address="form.drillAddress" @confirm="handleMapChange"></company-map>
</template>
<script setup lang="ts">
import { listDrill, addDrill, updateDrill, getDrillDetail, deleteDrill } from '@/api/riskPrevention/planManage';
import { to } from 'await-to-js';
import { ref } from 'vue';
import { download2 } from '@/utils/request';

const props = defineProps({
  id: String
});

const formRef = ref<ElFormInstance>();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const downLoadApi = import.meta.env.VITE_APP_BASE_DOWNLOAD_API;
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectedRow = ref(null);
const dataList = ref([]);
const loading = ref(true);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(['update:modelValue', 'getList']);
let visible = ref(false);
let buttonLoading = ref(false);
let title = ref('');
const queryParams = reactive({
  page: 1,
  pageSize: 10
});
const form = ref({
  drillId: '',
  drillName: '',
  drillUnit: '',
  year: '',
  drillTime: '',
  drillAddress: '',
  lon: '',
  lat: '',
  drillProject: '',
  drillVideo: '',
  drillPicture: ''
});
const rules = reactive({
  drillName: [{ required: true, message: '演练名称不能为空', trigger: 'blur' }],
  drillUnit: [{ required: true, message: '演练单位不能为空', trigger: 'blur' }],
  year: [{ required: true, message: '演练年度不能为空', trigger: 'blur' }],
  drillTime: [{ required: true, message: '演练时间不能为空', trigger: 'change' }],
  drillAddress: [{ required: true, message: '演练地点不能为空', trigger: 'blur' }],
  drillProject: [{ required: true, message: '演练方案不能为空', trigger: 'change' }],
  drillVideo: [{ required: true, message: '演练视频不能为空', trigger: 'change' }],
  drillPicture: [{ required: true, message: '演练图片不能为空', trigger: 'change' }]
});
const showVideo = ref(false);
const videoList = ref([]);

const handleShowVideo = (row) => {
  videoList.value = row;
  showVideo.value = true;
};

// 获取列表数据
const getList = () => {
  loading.value = true;
  listDrill({ ...queryParams, planNum: props.id })
    .then((res) => {
      res.data.forEach((item) => {
        if (item.drillPicture && item.drillPicture.length > 0) {
          let urlList = [];
          item.drillPicture.forEach((item2) => {
            urlList.push(baseUrl + downLoadApi + item2.url);
          });
          item.urlList = urlList;
          item.url = urlList[0];
        }
      });
      dataList.value = res.data;
      total.value = res.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

watch(
  () => props.id,
  () => {
    if (props.id) {
      getList();
    }
  },
  {
    immediate: true
  }
);

/** 取消按钮 */
const cancel = () => {
  resetForm();
  visible.value = false;
};

/**
 * 关闭用户弹窗
 */
const closeDialog = () => {
  emits('update:modelValue', false);
  resetForm();
};

const resetForm = () => {
  form.value = {
    drillId: '',
    drillName: '',
    drillUnit: '',
    year: '',
    drillTime: '',
    drillAddress: '',
    lon: '',
    lat: '',
    drillProject: '',
    drillVideo: '',
    drillPicture: ''
  };
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
};

const handleUpdate = async (row) => {
  if (row) {
    resetForm();
    const res = await getDrillDetail(row.drillId);
    form.value = res.data;
    visible.value = true;
    title.value = '修改演练记录';
  }
};

const handleAdd = () => {
  resetForm();
  visible.value = true;
  title.value = '添加演练记录';
};

/**提交按钮 */
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        buttonLoading.value = true;
        form.value.drillId ? await updateDrill({ ...form.value, planId: props.id }) : await addDrill({ ...form.value, planId: props.id });
        proxy?.$modal.msgSuccess(form.value.drillId ? '修改成功' : '新增成功');
        visible.value = false;
        getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.drillId);
  selectedRow.value = selection.length === 1 ? selection[0] : null;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleDelete = async (row) => {
  const deleteIds = row && row.drillId ? [row?.drillId] : ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除选择的演练记录？') as any);
  if (!err) {
    await deleteDrill(deleteIds);
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  }
};

// 下载
const handleDownload = (row) => {
  if (row.drillProject && row.drillProject.length > 0) {
    row.drillProject.forEach((file) => {
      download2(baseUrl + downLoadApi + file.url, file.name);
    });
  }
  if (row.drillVideo && row.drillVideo.length > 0) {
    row.drillVideo.forEach((file) => {
      download2(baseUrl + downLoadApi + file.url, file.name);
    });
  }
  if (row.drillPicture && row.drillPicture.length > 0) {
    row.drillPicture.forEach((file) => {
      download2(baseUrl + downLoadApi + file.url, file.name);
    });
  }
};

// 地图定位
const mapDialogVisible = ref(false);
const openMapDialog = () => {
  mapDialogVisible.value = true;
};
const handleMapChange = (data) => {
  form.value.drillAddress = data.address;
  form.value.lon = data.lnglat[0];
  form.value.lat = data.lnglat[1];
  mapDialogVisible.value = false;
};
</script>

<style lang="scss">
.video-box {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
