<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>
    <div class="formArea">
      <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
          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
          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"
          @click="showArea = true"
        />
        <van-popup v-model:show="showArea" round position="bottom">
          <van-cascader
            v-model="cascaderValue"
            title="请选择所在地区"
            :options="options"
            @close="showArea = false"
            @finish="onFinish"
            :field-names="fieldNames"
          />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="placeActivity.placeDel"
          center
          clearable
          label="详细地址:"
          placeholder="请填写活参加地点"
          input-align="right"
        >
          <template #right-icon>
            <van-icon name="location" />
          </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"></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="1"
              capture="camera"
              accept=""
            >
              <van-button>上传文件</van-button>
              <template #preview-cover="file">
                <div class="preview-cover van-ellipsis">{{ file.name }}</div>
              </template>
            </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>
    <div class="subbtn">
      <van-button type="primary" @click="submit">提交</van-button>
      <van-button type="default" hairline>取消</van-button>
    </div>
  </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);
    // 获取当前登录用户
    const user = new placeActivityServer().queryListLonginId().then((data) => {
      new tools().queryById(data.id).then((res) => {
        placeActivity.value.reporter = res;
      });
    });
    // 根据路由初始化
    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) {
              fileList.value.push({
                name: decodeURIComponent(
                  item.substring(item.lastIndexOf("/") + 1)
                ),
                url: $base + item,
              });
            }
          });
          subjectContentEditor.value.init(placeActivity.value.subjectContent);
          isLoading.value = false;
        });
      } else {
        subjectContentEditor.value.init(placeActivity.value.subjectContent);
        placeActivity.value.reporter = user;
        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];
    };
    // 获取活动时间
    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.activityPerson.name = list.value.name;
      }
    };
    // 地区选择
    let showArea = ref(false);
    const cascaderValue = ref("");
    const fieldNames = {
      text: "name",
      value: "code",
      children: "children",
    };
    // 选项列表，children 代表子选项，支持多级嵌套
    let options = ref([]);
    new tools().treeData().then((res) => {
      options.value.push(res[0]);
    });
    // 全部选项选择完毕后，会触发 finish 事件
    const onFinish = ({ selectedOptions }) => {
      showArea.value = false;
      placeActivity.value.place = selectedOptions
        .map((option) => option.name)
        .join("/");
    };
    // 文件上传
    let fileList = ref([]);
    const afterRead = (file) => {
      fileList.value = [];
      // 此时可以自行将文件上传至服务器
      new tools()
        .uploadFile(file, `reporting/reportingActivities`)
        .then(({ data }) => {
          placeActivity.value.safetyPlan = data.url;
          fileList.value.push(data);
          fileList.value[0].url = `${$base}` + fileList.value[0].url;
          fileList.value[0].name = decodeURIComponent(
            fileList.value[0].url.substring(
              fileList.value[0].url.lastIndexOf("/") + 1
            )
          );
        });
      console.log("上传文件", placeActivity.value.safetyPlan);
    };
    // 提交数据
    const submit = () => {
      isLoading.value = true;
      new placeActivityServer().save(placeActivity.value).then((res) => {
        console.log("提交", res);
        onClickLeft();
        isLoading.value = false;
      });
    };
    return {
      isLoading,
      placeActivity,
      // 活动场所
      customFieldName,
      showPlace,
      places,
      getPlace,
      // 活动时间
      showAct,
      columnsType,
      currentDate,
      currentTime,
      getTime,
      // 返回
      onClickLeft,
      // 人员选择
      showPerson,
      showReport,
      selected,
      reselected,
      // 地区选择
      showArea,
      fieldNames,
      options,
      onFinish,
      cascaderValue,
      // 文件上传
      afterRead,
      fileList,
      submit,
      subjectContentEditor,
    };
  },
};
</script>

<style scoped>
.van-cell__value .van-field__right-icon .van-icon-location {
  color: #36a7f3 !important;
}
.van-uploader .van-button {
  border: none;
  color: #36a7f3;
  top: -4px;
}
.van-dialog {
  width: 80%;
  top: 50%;
}
.van-loading {
  text-align: center;
  margin-top: 80px;
}
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>