
<script lang="ts">
export default {
  name: 'activitymanage' // 活动管理
};
</script>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";

import { queryActivityPage,addActivity,updateActivity,updateActivityStatus,delActivity } from "@/api/activity";
import Page from '@/components/Pagination/page.vue';
import Aactivityschool from './school.vue';
import Viewfile from "@/views/component/Viewfile.vue";
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const url = userStore.webApiBaseUrl;
const queryInfo :any = ref({
  current:1,
  size:10,
  total:0
})
//搜索内容
const activityname = ref('')
const activitytype = ref('')
const typeoptions:any = ref([{value:"01",label:"调查问卷"},{value:"02",label:"训练活动"},{value:"03",label:"科普宣传"}])
const tableData:any = ref([])
const multipleSelection = ref([])
const dialogFormVisible = ref(false)
const dialogtitle = ref('新增活动')
const form:any = ref({})
const planform = ref();

const rules = reactive<FormRules>({
  activity_type: [{ required: true, message: "请输入活动类型", trigger: "blur" }],
  activity_title: [{ required: true, message: "请输入活动名称", trigger: "blur" }]
});
function releaseClick(row:any){
  ElMessageBox.confirm("确定发布此活动吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: row.id,
      status:'02'
    };
    updateActivityStatus(params).then((res:any) => {
      ElMessage({
        message: "发布成功",
        type: "success",
      });
      getData()
    }).catch(()=>{

    })

  });
}
function delinfoStatus(row:any){
  ElMessageBox.confirm("确定删除此活动吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: row.id,
      status:'03'
    };
    updateActivityStatus(params).then((res:any) => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getData()
    }).catch(()=>{

    })

  });
}
function addinfo(){
  dialogtitle.value = '新增活动'
  schoolNames.value =''
  form.value = {}
  fileList.value = []
  isSwitch.value = false
  dialogFormVisible.value = true
}
function editinfo(row:any){
  form.value = JSON.parse(JSON.stringify(row))
  if(form.value.school_ids != null && form.value.school_ids != ""){
    form.value.school_ids = JSON.parse(form.value.school_ids)
    let temp = []
    for(let i=0;i<form.value.school_ids.length;i++){
      temp.push(form.value.school_ids[i].name)
    }
    schoolNames.value = temp.join(",")
  }else{
    form.value.school_ids = []
  }

  isSwitch.value = false
  dialogtitle.value = '修改活动'
  //  res.data.records[i].activityNames.push(filespath[a])
  //           res.data.records[i].activityFiles.push(url + '/activity/' + filespath[a])
  fileList.value = []
  if (row.activityNames != '' && row.activityNames != null) {
    for (let i = 0; i < row.activityNames.length; i++) {
      fileList.value.push({
        name: row.activityNames[i],
        url: row.activityFiles[i],
      })
    }
  }
  dialogFormVisible.value = true
 
}
const isSwitch = ref(false)
function infosubmit(formEl: any){
  console.log(fileList.value)
  formEl.validate((valid: any) => {
    if (valid) {
      if(isSwitch.value == true){
        return
      }
      isSwitch.value = true
      if (form.value.id) {
        const formData = new FormData();
        let activityFiles:any = []
        fileList.value.forEach((item: any) => {
          if (item.raw != null) {
            formData.append('multipartFile', item.raw)
          }else {
              activityFiles.push(item.name)
          }
        })
        if(activityFiles.length == 0){
          form.value.activity_files = ""
        }else{
          form.value.activity_files = activityFiles.join(",")
        }
        formData.append("activityFiles", form.value.activity_files);
        if(form.value.id !=null) formData.append("id", form.value.id);
        if(form.value.activity_code !=null) formData.append("activityCode", form.value.activity_code);
        if(form.value.activity_title !=null) formData.append("activityTitle", form.value.activity_title);
        if(form.value.activity_type !=null) formData.append("activityType", form.value.activity_type);
        if(form.value.activity_desc !=null) formData.append("activityDesc", form.value.activity_desc);
        if(form.value.activity_date !=null) formData.append("activityDate", form.value.activity_date);
        if(form.value.school_ids !=null){
          formData.append("schoolIds", JSON.stringify(form.value.school_ids));
        }else{
          form.value.school_ids = []
          formData.append("schoolIds", JSON.stringify(form.value.school_ids));
        }
        if(form.value.publicOrg !=null) formData.append("publicOrg", form.value.public_org);
        updateActivity(formData).then((item) => {
          dialogFormVisible.value = false;
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          getData();
        }).catch(()=>{
          isSwitch.value = false
        })
      } else {
        const formData = new FormData();
        fileList.value.forEach((item: any) => {
          if (item.raw != null) {
            formData.append('multipartFile', item.raw)
          }
        })
 
        if(form.value.activity_code !=null) formData.append("activityCode", form.value.activity_code);
        if(form.value.activity_title !=null) formData.append("activityTitle", form.value.activity_title);
        if(form.value.activity_type !=null) formData.append("activityType", form.value.activity_type);
        if(form.value.activity_desc !=null) formData.append("activityDesc", form.value.activity_desc);
        if(form.value.activity_date !=null) formData.append("activityDate", form.value.activity_date);
        if(form.value.school_ids !=null){
          formData.append("schoolIds", JSON.stringify(form.value.school_ids));
        }else{
          form.value.school_ids = []
          formData.append("schoolIds", JSON.stringify(form.value.school_ids));
        }
        if(form.value.publicOrg !=null) formData.append("publicOrg", form.value.public_org);
        addActivity(formData).then((item) => {
          dialogFormVisible.value = false;
          getData();
          ElMessage({
            message: "新增成功",
            type: "success",
          });
        }).catch(()=>{
          isSwitch.value = false
        })
      }
 
    }
  })
}
function handlefilechange(file:any){
console.log(file)
}

function delinfo(row: any) {
  ElMessageBox.confirm("确定删除此活动吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      ids: row.id,
    };
    delActivity(params).then((res:any) => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getData()
    }).catch(()=>{

    })

  });
}
function delinfos() {
  ElMessageBox.confirm("确定删除已选择的年级吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.id)
    })
    let params = {
      ids: id.join(','),
    };
    delActivity(params).then(() => {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
const loading =ref(false)
function getData(){

  loading.value = true
  activityname.value = activityname.value.replace(/\s+/g, "");
  let params = {
    activityTitle: activityname.value,
    activityType: activitytype.value,
    current: queryInfo.value.current,
    size:queryInfo.value.size
  };
  loading.value = true
  queryActivityPage(params).then((res:any) => {
    for (let i = 0; i < res.data.records.length; i++) {
      if (res.data.records[i].activity_files != '' && res.data.records[i].activity_files != null) {
        let filespath = res.data.records[i].activity_files.split(',')
        res.data.records[i].activityNames = []
        res.data.records[i].activityFiles = []
        for (let a = 0; a < filespath.length; a++) {
          res.data.records[i].activityNames.push(filespath[a])
          res.data.records[i].activityFiles.push(url + '/activity/' + filespath[a])
        }
      }
    }
    tableData.value = res.data.records;
    queryInfo.value.total = res.data.total
    loading.value = false
  });

}
function searchinfo(){

}
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
function handleClose(){
  if (planform.value != null) planform.value.resetFields();
  dialogFormVisible.value = false
}

const isViewfile = ref(false)
const ViewfileUrl = ref("")
function viewpdf(name: any) {
  ViewfileUrl.value =  url + '/vision_examine/activity/viewActivityFile?fileName=' + name
  setTimeout(()=>{
    isViewfile.value = true
  },200)

}
function CloseView() {
  isViewfile.value = false
}
const isSchool = ref(false)
function schoolClick(){
  isSchool.value = true
}
function returnClick(data:any){
  if(data == false){
    isSchool.value = false
  }else{
    let temp = []
    let tempData = []
    for(let i=0;i<data.length;i++){
      temp.push(data[i].name)
      tempData.push({
        id:data[i].id,
        name:data[i].name,
      })
    }
    schoolNames.value = temp.join(",")
    form.value.school_ids =  tempData
    isSchool.value = false
  }
}
const schoolNames = ref("")
onMounted(() => {
  getData();
});
const fileList:any = ref([
])
function dateFormat(row: any) { // 时间方法
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}
</script>
<template>
    <div class="w-full">
      <div class="activitymanage-box">
        <div class="activitymanage-box-top">
          <div class="flex">
            <el-input v-model="activityname" placeholder="请输入活动名称" style="width:240px" clearable />
            <el-select v-model="activitytype" class="ml-4" placeholder="请选择活动类型" style="width: 240px" clearable @change="getData">
              <el-option v-for="item in typeoptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
            <el-button type="primary" class="ml-[10px]" @click="getData">搜索</el-button>
          </div>
          <div>
            <el-button type="primary" @click="addinfo"><img src="@/assets/visionscreening/jscz_xz.png" alt="" style="margin-right: 4px;" >新增</el-button>
          <!-- <el-button @click="delinfos" :disabled="multipleSelection.length <= 0" :type="multipleSelection.length > 0 ? 'primary' : ''">
            <el-icon><Delete /></el-icon> 删除</el-button> -->
          </div>
        </div>
        <div class="visionscreening-box-bottom">
          <el-table :data="tableData" border style="width: 100%; height:calc(100vh - 280px)" @selection-change="handleSelectionChange" :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="55" label="序号" />
            <el-table-column prop="activity_code" label="活动编号" width="120" />
            <el-table-column prop="activity_title" label="活动名称" min-width="140" />
            <el-table-column prop="activity_type" label="活动类型" width="120" align="center">
              <template #default="scope">
                <span v-if="scope.row.activity_type == '01'">调查问卷</span>
                <span v-if="scope.row.activity_type == '02'">训练活动</span>
                <span v-if="scope.row.activity_type == '03'">科普宣传</span>
              </template>
            </el-table-column>
            <el-table-column prop="activity_date" label="活动开始日期" width="180" align="center"/>
            <el-table-column prop="org_type" label="文件" width="80" align="center" >
              <template #default="scope">
                <div v-if="scope.row.activityFiles !== '' &&scope.row.activityFiles !== undefined" style="display:flex ;flex-wrap: wrap;">
                  <img v-for="(item,index) in scope.row.activityFiles" src="@/assets/visionscreening/pdficon.png" style="margin: 0 auto;cursor: pointer;" @click="viewpdf(scope.row.activityNames[index])" :title="scope.row.activityNames[index]">
                </div>
                <div v-else></div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="活动状态" width="180" align="center">
              <template #default="scope">
                <span v-if="scope.row.status == '01'">初始创建</span>
                <span v-if="scope.row.status == '02'">发布活动</span>
                <span v-if="scope.row.status == '03'">活动关闭</span>
              </template>
            </el-table-column>
            <el-table-column prop="public_org" label="发布单位" width="180" />
            <el-table-column prop="creator" width="120" label="创建人"  align="center"/>
            <el-table-column prop="create_time" width="180" label="创建时间"  align="center" >
              <template #default="scope">
              {{ dateFormat(scope.row.create_time) }}
            </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="100" fixed="right" align="center">
              <template #default="scope">
                <div style="display: -webkit-flex;display: flex; justify-content: space-around;-webkit-justify-content: space-around; ">
                  <img v-if="scope.row.status =='01'" src="@/assets/MenuIcon/lbcz_xg.png" alt="" title="修改" @click="editinfo(scope.row)" style="cursor: pointer;">
                  <img v-if="scope.row.status =='01'" src="@/assets/MenuIcon/release.png" alt="" title="发布" @click="releaseClick(scope.row)" style="cursor: pointer;">

                  <img v-if="scope.row.status =='01'" src="@/assets/MenuIcon/lbcz_sc.png" alt="" title="删除" @click="delinfo(scope.row)" style="cursor: pointer;">
                  <img v-if="scope.row.status =='02'" src="@/assets/MenuIcon/lbcz_sc.png" alt="" title="删除" @click="delinfoStatus(scope.row)" style="cursor: pointer;">
                </div>
              </template>
            </el-table-column>
          </el-table>
          <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size" v-model:current="queryInfo.current"
          @pagination="getData" />
        </div>
      </div>
      <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" :title="dialogtitle" :before-close="handleClose" width="43%" draggable append-to-body>
        <el-form ref="planform" :model="form" :rules="rules" label-width="90px">
          
          <div class="flex justify-between ">
            <el-form-item label="活动编码" style="width: 50%">
              <el-input v-model="form.activity_code" placeholder="添加成功后自动生成编码" disabled/>
            </el-form-item>
            <el-form-item label="活动名称" prop="activity_title" style="width: 50%">
              <el-input v-model="form.activity_title" autocomplete="off"  placeholder="请输入计划编号" />
            </el-form-item>
         </div>
         <div class="flex justify-between ">
            <el-form-item label="开始时间" style="width: 50%">
              <el-date-picker
                 style="width: 100%;"
                  v-model="form.activity_date"
                  type="date"
                  placeholder=""
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item label="活动类型" prop="activity_type" style="width: 50%">
                <el-select v-model="form.activity_type" placeholder="请选择活动类型" >
                <el-option v-for="item in typeoptions" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
            </el-form-item>
         </div>
        <el-form-item label="关联学校">
          <div class="flex w-full h-[32px]">
            <el-input v-model="schoolNames" autocomplete="off" style="margin-right: 5px;"  size="large" disabled placeholder="请选择关联的学校" />
            <el-button type="primary" class="ml-[10px]" @click="schoolClick">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="发布单位">
            <el-input v-model="form.public_org" placeholder="请输入发布单位"/>
        </el-form-item>
        <el-form-item label="活动描述">
            <el-input v-model="form.activity_desc" :autosize="{ minRows: 4 }" type="textarea" placeholder="请输入活动描述"/>
        </el-form-item>
        
        <el-form-item label="活动文件">
          <div style="width:100% ;">
            <el-upload  ref="upload"  accept=".PDF,.pdf" class="upload-demo" action="" :on-change="handlefilechange" :auto-upload="false"
            v-model:file-list="fileList">
              <template #trigger>
                <el-button type="primary">上传</el-button>
              </template>
            </el-upload>
          </div>
          
        </el-form-item>
        </el-form>
        <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="infosubmit(planform)">确定</el-button>
        </span>
      </el-dialog>
      
      <Aactivityschool v-if="isSchool==true" @returnClick="returnClick" />
      <Viewfile v-if="isViewfile" :showTime="true" :title="'查看活动'" :url="ViewfileUrl" :type="'pdf'" :clientHeight="600"
        @update="CloseView" :onprint="'no'" />
    </div>
</template>
<style scoped  lang="scss">

.activitymanage-box {
  height: calc(100vh - 130px);
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0px 0px 10px rgba(219, 225, 236, 1);
  padding: 20px;
  .activitymanage-box-top{
    width:100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
.dialog-footer {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}
:deep(.el-tree-node__content){
  height: 30px;
}
:deep(.el-input__inner){
  height: 32px;
  font-size:14px;
}
// :deep(.el-upload-list){
// display: none;
// }
.lefttitle {
  min-width: 150px;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #1B1B1B;
  background: rgba(246, 247, 250, 1);
  border-bottom: 1px var(--el-border-color) var(--el-border-style);
  margin-bottom: 10px;
  .line{
    border-width: 0px;
    width: 5px;
    height: 14px;
    margin-right: 7px;
    background: inherit;
    background-color: rgba(64, 158, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}
.leftbox{
  width: 250px;
  height: calc(100vh - 200px);
  border: 1px solid #e1e1e1;
  border-radius: 4px;
}
</style>
