<template>
  <van-nav-bar fixed title="信教异常群众信息上报" left-text="" left-arrow @click-left="onClickLeft" />
  <van-loading size="16px" v-if="isLoading">加载中...</van-loading>
  <div class="main" v-if="!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="religiousType" center readonly 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="$dictUtils.getDictList('hs_religion_type')" :columns-field-names="{
            text: 'label',
            value: 'value'
          }" @cancel="showPlace = false" @confirm="getType" />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="inputForm.abnormalName" center label="异常人员:" placeholder="请填写异常人员姓名" input-align="right" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="inputForm.abnormalIdcar" center label="身份证号:" placeholder="请填写身份证号" input-align="right"
          type="digit" />
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="inputForm.abnormalPhone" center label="手机号:" placeholder="请填写手机号" input-align="right"
          type="tel" />
      </van-cell-group>
      <van-cell-group>
        <van-field name="radio" label="性别:" input-align="right">
          <template #input>
            <van-radio-group v-model="inputForm.sex" direction="horizontal">
              <van-radio name="1">男</van-radio>
              <van-radio name="2">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="inputForm.nativePlace" center readonly label="籍贯:" placeholder="请选择籍贯" input-align="right"
          right-icon="arrow-down" @click="showArea = true" />
        <van-popup v-model:show="showArea" round position="bottom">
          <van-picker title="籍贯选择" :columns="options" :columns-field-names="customFieldName" @cancel="showArea = false"
            @confirm="onFinish2" />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="inputForm.currentResidence" center readonly label="现居地:" placeholder="请选择现居地"
          input-align="right" right-icon="arrow-down" @click="showCurrentArea = true" />
        <van-popup v-model:show="showCurrentArea" round position="bottom">
          <van-picker title="现居地选择" :columns="options" :columns-field-names="customFieldName"
            @cancel="showCurrentArea = false" @confirm="onFinish" />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field v-model="inputForm.currentResidenceDetail" center label="现居地详情:" placeholder="请填写现居地详情"
          input-align="right">
          <template #right-icon>
            <van-icon name="location" @click="getLocation" />
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <div class="rowTextArea">
          <van-field v-model="inputForm.abnormalBehavior" required :rules="[{ required: true }]" placeholder="请填写异常行为"
            center rows="2" type="textarea" label="异常行为:" label-align="top" />
        </div>
      </van-cell-group>
      <van-cell-group>
        <van-field name="uploader" required :rules="[{ required: true }]" 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>
      <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, getCurrentInstance } from "vue";
import { useCascaderAreaData } from "@vant/area-data";
import ReligiousPeopleReportService from "@/api/differentbelievers/ReligiousPeopleReportService";
import { useRoute } from "vue-router";
import tools from "@/api/sys/tools";
// 图片路径
import $base from "@/utils/config";
export default {
  setup() {
    // 返回
    const onClickLeft = () => {
      history.back();
    };
    // 加载
    let isLoading = ref(true);
    // 异常人员信息
    const inputForm = ref({
      id: '',
      abnormalName: '',
      religiousType: '',
      information: '',
      abnormalIdcar: '',
      sex: '',
      abnormalPhone: '',
      nativePlace: '',
      currentResidence: '',
      currentResidenceDetail: '',
      abnormalBehavior: '',
      state: '0',
      assessment: '0',
      currentResidenceId: '',
      currentResidenceLevel1: '',
      currentResidenceLevel2: '',
      currentResidenceLevel3: '',
      currentResidenceLevel4: '',
      currentResidenceLevel5: '',
      currentResidenceLevel6: ''
    });
    const current = getCurrentInstance()
    // 根据路由初始化
    let route = useRoute();
    onMounted(() => {
      //籍贯接口
      new tools().nativePlace().then((res) => {
        options.value.push(...res);
      });
      if (route.query.id) {
        new ReligiousPeopleReportService()
          .queryById(route.query.id)
          .then((data) => {
            inputForm.value = data;
            religiousType.value = current.appContext.config.globalProperties.$dictUtils.getDictLabel('hs_religion_type', inputForm.value.religiousType)
            inputForm.value.information.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("程序附件//", "程序附件/")
                });
              }
            });
            isLoading.value = false;
          });
      } else {
        isLoading.value = false;
      }
    });
    // 现居地选择
    const showCurrentArea = ref(false);
    const customFieldName = {
      text: "name",
      value: "id",
    };
    // 选项列表，children 代表子选项，支持多级嵌套
    const options = ref([]);
    // 全部选项选择完毕后，会触发 finish 事件
    const onFinish = ({ selectedOptions }) => {
      showCurrentArea.value = false;
      console.log(selectedOptions);
      inputForm.value.currentResidence = selectedOptions
        .map((option) => option.name)
        .join("/");
      inputForm.value.currentResidenceId = selectedOptions
        .map((option) => option.id)
        .join("/");

      inputForm.value.currentResidenceLevel1 = selectedOptions[0] ? selectedOptions[0].id : ''
      inputForm.value.currentResidenceLevel2 = selectedOptions[1] ? selectedOptions[1].id : ''
      inputForm.value.currentResidenceLevel3 = selectedOptions[2] ? selectedOptions[2].id : ''
      inputForm.value.currentResidenceLevel4 = selectedOptions[3] ? selectedOptions[3].id : ''
      inputForm.value.currentResidenceLevel5 = selectedOptions[4] ? selectedOptions[4].id : ''
      inputForm.value.currentResidenceLevel6 = selectedOptions[5] ? selectedOptions[5].id : ''
    }
    const getLocation = () => {
      xm.getLocation().then(data => {
        inputForm.value.currentResidenceDetail = data.POIName;
      })
    }
    // 籍贯选择
    let showArea = ref(false);
    // 全部选项选择完毕后，会触发 finish 事件
    const onFinish2 = ({ selectedOptions }) => {
      showArea.value = false;
      inputForm.value.nativePlace = selectedOptions
        .map((option) => option.name)
        .join("/");
    };
    const getType = ({ selectedOptions }) => {
      showPlace.value = false;
      inputForm.value.religiousType = selectedOptions[0].value;
      religiousType.value = selectedOptions[0].label
    };
    // 文件上传
    let fileList = ref([]);
    let fileupList = ref([]);
    const chooseImg = () => {
      xm.chooseFile({
        count: 1,
        name: "file",
        url: $base + `/sys/file/webupload/upload?uploadPath=differentbelievers/religiousPeopleReport`,
        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;
      //保存前附件处理
      inputForm.value.information = fileupList.value
        .map((option) => option.id)
        .join("|");
      new ReligiousPeopleReportService().save(inputForm.value).then((res) => {
        if (res.status == 200 || res.statusText == "OK") {
          xm.showToast({
            message: res.data,
          });
        }
        onClickLeft();
      });
    };
    let showPlace = ref(false);
    let religiousType = ref('');
    return {
      inputForm,
      religiousType,
      // 返回
      onClickLeft,
      // 地区选择
      showArea,
      options,
      onFinish,
      onFinish2,
      customFieldName,
      isLoading,
      getType,
      // 文件上传
      chooseImg,
      deleteRead,
      fileList,
      submit,
      showCurrentArea,
      showPlace,
      getLocation
    };
  },
};
</script>
    
<style scoped>
.van-uploader .van-button {
  border: none;
  color: #36a7f3;
  top: -4px;
}

.rowTextArea::v-deep .van-field__value {
  width: 98%;
  border: 2px solid #ccc;
  border-radius: 10px;
  padding-left: 10px;
}

.rowTextArea::v-deep .van-cell {
  display: flow-root;
}

.van-radio {
  margin-right: 10px;
}
</style>