<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-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 required :rules="[{ required: true }]" 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 @selected="selected" :type="1"></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.name" center label="活动负责人:" placeholder="请选择活动负责人"
          input-align="right" right-icon="arrow-down" @click="showReport = true" />
        <van-dialog v-model:show="showReport" title="选择活动负责人" show-cancel-button @confirm="reselected">
          <person-list @selected="selected" :type="0" ref="person"></person-list>
        </van-dialog>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="placeActivity.phone" center readonly type="tel" label="联系方式:" placeholder="请填写联系方式"
          input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field name="uploader" label="安全预案:">
          <template #input>
            <van-uploader :after-read="afterRead" v-model="fileList" :max-count="5" capture="camera" accept=""
              :preview-full-image="false" :before-delete="deleteRead">
              <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 $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: "",
      siteName: {
        id: "",
        name: "",
      },
      activityTime: "",
      participantsNum: "",
      knownList: {
        id: "",
        name: "",
      },
      subjectContent: "",
      reporter: {
        id: "",
        name: "",
      },
      participation: "",
      place: "",
      placeDel: "",
      sourceFunds: "",
      safetyPlan: "",
      activityPerson: {
        id: "",
        name: "",
      },
      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({
                file: {
                  name: decodeURIComponent(
                    item.substring(item.lastIndexOf("/") + 1)
                  ),
                },
                url: item,
              });
              fileList.value.push({
                file: {
                  name: decodeURIComponent(
                    item.substring(item.lastIndexOf("/") + 1)
                  ),
                },
                url: $base + 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([]);
    const customFieldName = {
      text: "name",
      value: "id",
    };
    new tools()
      .placeList({
        current: 1,
        size: 10000,
      })
      .then(({ records }) => {
        places.value.push(...records);
      });
    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;
    };
    const getLocation = () => {
      xm.getLocation().then(data => {
        placeActivity.value.placeDel = data.POIName;
      })
    }
    // 获取活动时间
    let showAct = ref(false);
    let currentDate = ref(["" + new Date().getFullYear(), "01", "01"]);
    let currentTime = ref(["00", "00", "00"]);
    const columnsType = ["hour", "minute", "second"];
    const getTime = () => {
      showAct.value = false;
      placeActivity.value.activityTime = `${currentDate.value.join(
        "-"
      )} ${currentTime.value.join(":")}`;
    };
    // 已知名单
    let showPerson = ref(false);
    // 活动负责人
    let showReport = 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(",");
      } else {
        placeActivity.value.activityPerson.id = list.value.id;
        placeActivity.value.phone = list.value.phone;
        placeActivity.value.activityPerson.name = list.value.name;
      }
    };
    // 文件上传
    let fileList = ref([]);
    let fileupList = ref([]);
    const afterRead = (file) => {
      file.status = "uploading";
      file.message = "上传中";
      // 此时可以自行将文件上传至服务器
      new tools()
        .uploadFile(file, `reporting/reportingActivities`)
        .then(({ data, status, statusText }) => {
          if (status == 200 || statusText == "OK") {
            file.status = "done";
            // xm.showToast({
            //   message: "上传成功",
            // });
            data.name = decodeURIComponent(
              data.url.substring(data.url.lastIndexOf("/") + 1)
            );
            fileupList.value.push(data);
          }
        })
        .catch(() => {
          file.status = "failed";
          file.message = "上传失败";
        });
    };
    // 删除文件
    const deleteRead = (file) => {
      //删除文件操作
      for (let index = 0; index < fileList.value.length; index++) {
        if (file.file.name == fileList.value[index].file.name) {
          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.url)
        .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,
      getPlace,
      getLocation,
      // 活动时间
      showAct,
      columnsType,
      currentDate,
      currentTime,
      getTime,
      // 返回
      onClickLeft,
      // 人员选择
      showPerson,
      showReport,
      selected,
      reselected,
      // 文件上传
      afterRead,
      deleteRead,
      fileList,
      submit,
      subjectContentEditor,
    };
  },
};
</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>