<template>
  <van-nav-bar fixed title="场所活动信息上报" left-text="" left-arrow @click-left="onClickLeft" />
  <van-loading size="16px" v-show="isLoading">加载中...</van-loading>
  <div class="main" v-show="!isLoading">
    <!-- <p class="title">场所活动上报</p> -->
    <van-form class="formArea" @submit="submit" show-error :show-error-message="false" validate-trigger="onChange">
      <!-- <p class="miniTitle">基础信息</p> -->
      <van-cell-group>
        <van-field v-model="placeActivity.activityName" center clearable label="活动名称:" placeholder="请填写活动名称"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.siteName.name" readonly required :rules="[{ required: true }]" label="场所名称:"
          placeholder="请选择场所名称" input-align="right" right-icon="arrow-down" @click="showPlace = true" />
        <van-popup v-model:show="showPlace" round position="bottom">
          <van-search placeholder="请输入场所名称" shape="round" input-align="center" v-model="interSearch" show-action
            @search="onSearch" @cancel="onCancel" />
          <van-picker title="活动场所" :columns="places" :columns-field-names="customFieldName" @cancel="showPlace = false"
            @confirm="getPlace" />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.activityTime" center readonly label="活动时间:" placeholder="请选择时间"
          input-align="right" right-icon="arrow-down" @click="showAct = true" />
        <van-popup v-model:show="showAct" round position="bottom">
          <van-picker-group title="活动时间" :tabs="['选择日期', '选择时间']" next-step-text="下一步" @confirm="getTime"
            @cancel="showAct = false">
            <van-date-picker v-model="currentDate" />
            <van-time-picker v-model="currentTime" :columns-type="columnsType" />
          </van-picker-group>
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.participantsNum" center clearable label="参会人数:" placeholder="请填写参会人数"
          input-align="right" type="digit" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.knownList.name" center label="已知名单:" placeholder="请选择参会已知名单" input-align="right"
          right-icon="arrow-down" @click="showPerson = true" />
        <van-dialog v-model:show="showPerson" title="选择人员名单" show-cancel-button @confirm="reselected">
          <person-list v-if="showPerson" @selected="selected" :type="1" :siteId="placeActivity.siteName.id"></person-list>
        </van-dialog>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.reporter.name" center readonly label="报告人:" placeholder="请选择报告人"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.participation" center clearable label="参加范围:" placeholder="请填写参加范围"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.place" center readonly label="活动地点:" placeholder="请选择场所" input-align="right"
          right-icon="arrow-down" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.placeDel" center readonly label="详细地址:" placeholder="请选择场所" input-align="right">
          <template #right-icon>
            <van-icon name="location" @click="getLocation" />
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.sourceFunds" center clearable label="经费来源:" placeholder="请填写经费来源"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.activityPerson" center label="活动负责人:" placeholder="请填写活动负责人"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.phone" center type="tel" label="联系方式:" placeholder="请填写联系方式"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field name="uploader" label="安全预案:">
          <template #input>
            <van-uploader readonly v-model="fileList" :max-count="5" accept="" :preview-full-image="false"
              :before-delete="deleteRead" @click-upload="chooseImg">
              <van-button>上传文件(可添加图片、音、视频和文本等)</van-button>
            </van-uploader>
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <van-field name="content" label="主题内容:" label-align="top">
          <template #input>
            <wang-editor ref="subjectContentEditor" v-model="placeActivity.subjectContent" />
          </template>
        </van-field>
      </van-cell-group>
      <div class="subbtn">
        <van-button type="primary" native-type="submit">提交</van-button>
        <van-button type="default" hairline @click="onClickLeft">取消</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import personList from "../personList.vue";
import placeActivityServer from "@/api/placeActivity/placeActivityServer";
import tools from "@/api/sys/tools";
import UserManage from "@/api/user/UserManage";
import { useRoute } from "vue-router";
import { formatDate, formatTime } from "@/utils/datatime";
// 图片路径
import $base from "@/utils/config";
// 富文本编辑器
import WangEditor from "@/components/editor/WangEditor";

export default {
  components: { personList, WangEditor },
  setup() {
    // 加载
    let isLoading = ref(true);
    // 返回
    const onClickLeft = () => {
      history.back();
    };
    // 活动信息
    let placeActivity = ref({
      id: "",
      activityName: "",
      activitiesType: "1",
      siteName: {
        id: "",
        name: "",
      },
      activityTime: "",
      participantsNum: "",
      knownList: {
        id: "",
        name: "",
      },
      subjectContent: "",
      reporter: {
        id: "",
        name: "",
      },
      participation: "",
      place: "",
      placeDel: "",
      sourceFunds: "",
      safetyPlan: "",
      activityPerson: "",
      phone: "",
      state: "0",
      assessment: "0",
    });
    // 富文本编辑器
    const subjectContentEditor = ref(null);
    // 根据路由初始化
    let route = useRoute();
    onMounted(() => {
      if (route.query.id) {
        new placeActivityServer().queryById(route.query.id).then((data) => {
          placeActivity.value = data;
          let ids = data.knownList.id.split(",");
          placeActivity.value.knownList.name = "";
          ids.forEach((item) => {
            new UserManage().queryById(item).then((data) => {
              placeActivity.value.knownList.name += data.name + ",";
            });
          });
          placeActivity.value.safetyPlan.split("|").forEach((item) => {
            if (item.trim().length > 0) {
              fileupList.value.push({
                name: decodeURIComponent(
                  item.substring(item.lastIndexOf("/") + 1)
                ),
                url: $base + item.replace("程序附件//", "程序附件/"),
                id: item.replace("程序附件//", "程序附件/")
              });
              fileList.value.push({
                name: decodeURIComponent(
                  item.substring(item.lastIndexOf("/") + 1)
                ),
                url: $base + item.replace("程序附件//", "程序附件/"),
                id: item.replace("程序附件//", "程序附件/")
              });
            }
          });
          subjectContentEditor.value.init(placeActivity.value.subjectContent);
          isLoading.value = false;
        });
      } else {
        subjectContentEditor.value.init(placeActivity.value.subjectContent);
        // 获取当前登录用户
        new placeActivityServer().queryListLonginId().then((data) => {
          new tools().queryById(data.id).then((res) => {
            placeActivity.value.reporter = res;
          });
        });
        isLoading.value = false;
      }
    });
    // 场所名称
    let places = ref([]);
    // 场所搜索
    let interSearch = ref("");
    const onCancel = () => {
      interSearch.value = "";
      places.value = [];
      placelist();
    };
    const onSearch = () => {
      places.value = [];
      new tools()
        .placeList({
          current: 1,
          size: 10000,
          name: interSearch.value
        })
        .then(({ records }) => {
          places.value.push(...records);
        });
    };
    const customFieldName = {
      text: "name",
      value: "id",
    };
    const placelist = () => {
      new tools()
        .placeList({
          current: 1,
          size: 10000,
        })
        .then(({ records }) => {
          places.value.push(...records);
        });
    }
    placelist();
    let showPlace = ref(false);
    const getPlace = ({ selectedOptions }) => {
      showPlace.value = false;
      placeActivity.value.siteName = selectedOptions[0];
      placeActivity.value.place = selectedOptions[0].placeSelectName;
      placeActivity.value.placeDel = selectedOptions[0].place;
      let searchForm = {
        location: {
          id: selectedOptions[0].id
        }
      }
      new UserManage()
        .list({
          current: 1,
          size: 10000,
          ...searchForm
        }).then(({ records }) => {
          placeActivity.value.knownList.name = "";
          placeActivity.value.knownList.id = "";
          records.forEach((item) => {
            placeActivity.value.knownList.name += item.name + ",";
            placeActivity.value.knownList.id += item.id + ",";
          });
        })
    };
    const getLocation = () => {
      xm.getLocation().then(data => {
        placeActivity.value.placeDel = data.POIName;
      })
    }
    // 获取活动时间
    let showAct = ref(false);
    let currentDate = ref(formatDate(new Date()));
    let currentTime = ref(formatTime(new Date()));
    const columnsType = ["hour", "minute", "second"];
    const getTime = () => {
      showAct.value = false;
      placeActivity.value.activityTime = `${currentDate.value.join(
        "-"
      )} ${currentTime.value.join(":")}`;
    };
    // 已知名单
    let showPerson = ref(false);
    let list = {
      value: [],
      type: "",
    };
    const selected = (val, type) => {
      list.value = val;
      list.type = type;
    };
    const reselected = () => {
      let ids = [];
      let names = [];
      if (list.type == 1) {
        list.value.forEach((item) => {
          ids.push(item.id);
          names.push(item.name);
        });
        placeActivity.value.knownList.id = ids.join(",");
        placeActivity.value.knownList.name = names.join(",");
      }
    };
    // 文件上传
    let fileList = ref([]);
    let fileupList = ref([]);
    const chooseImg = () => {
      xm.chooseFile({
        count: 1,
        name: "file",
        url: $base + `/sys/file/webupload/upload?uploadPath=reporting/reportingActivities`,
        headers: { 'Content-Type': 'multipart/form-data', "token": window.localStorage.getItem('MZ_TOKEN') },
      }).then(res => {
        let data = res[0].data
        data.name = decodeURIComponent(
          data.id.substring(data.url.lastIndexOf("/") + 1)
        );
        data.url = $base + data.url;
        fileupList.value.push(data);
        fileList.value.push(data)
      })
    }

    // 删除文件
    const deleteRead = (file) => {
      //删除文件操作
      for (let index = 0; index < fileList.value.length; index++) {
        if (file.id == fileList.value[index].id) {
          fileList.value.splice(index, 1);
          if (fileupList.value[index]) {
            let delurl = fileupList.value[index].url;
            new tools().uploadFiledelete("", delurl).then(({ data }) => { });
            fileupList.value.splice(index, 1);
          }
        }
      }
    };
    // 提交数据
    const submit = () => {
      isLoading.value = true;
      //保存前附件处理
      placeActivity.value.safetyPlan = fileupList.value
        .map((option) => option.id)
        .join("|");
      new placeActivityServer().save(placeActivity.value).then((res) => {
        if (res.status == 200 || res.statusText == "OK") {
          // xm.showToast({
          //   message: res.data,
          // });
        }
        onClickLeft();
      });
    };

    return {
      isLoading,
      placeActivity,
      // 活动场所
      customFieldName,
      showPlace,
      places,
      interSearch,
      onSearch,
      onCancel,
      getPlace,
      getLocation,
      // 活动时间
      showAct,
      columnsType,
      currentDate,
      currentTime,
      getTime,
      // 返回
      onClickLeft,
      // 人员选择
      showPerson,
      selected,
      reselected,
      // 文件上传
      deleteRead,
      fileList,
      submit,
      subjectContentEditor,
      chooseImg
    };
  },
};
</script>

<style scoped>
.van-uploader .van-button {
  border: none;
  color: #36a7f3;
  top: -4px;
}

.van-dialog {
  width: 80%;
  top: 50%;
}

.van-loading {
  text-align: center;
  margin-top: 80px;
}
</style>