<template>
  <van-nav-bar
    fixed
    title="牌位详细信息"
    left-arrow
    @click-left="onClickLeft"
    :style="{ 'background-color': selectColor }"
  />
  <div class="main">
    <div class="banner">
      <img src="../../../../public/loginbg/banner.jpg" alt="" />
    </div>
    <div class="info">
      <p class="miniTitle">牌位信息-{{ dataitem.brandName }}</p>
      <van-cell-group>
        <van-field
          v-model="dataitem.brandName"
          center
          required
          label="牌位名称:"
          placeholder="请填写牌位名称"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="locationName"
          readonly
          required
          label="所属场所："
          placeholder="请选择所属场所"
          input-align="right"
          right-icon="arrow-down"
          @click="hs_site = true"
        >
        </van-field>
        <van-dialog v-model:show="hs_site" title="所属场所" show-cancel-button>
          <div class="dialog">
            <van-list
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <van-radio-group v-model="checked">
                <van-cell-group inset>
                  <van-cell
                    v-for="item in sitelist"
                    :key="item"
                    :title="item.name"
                    clickable
                    @click="getsite(item)"
                  >
                    <template #right-icon>
                      <van-radio :name="item.id" />
                    </template>
                  </van-cell>
                </van-cell-group>
              </van-radio-group>
            </van-list>
          </div>
        </van-dialog>
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.siteContact"
          center
          disabled
          label="场所联系人:"
          placeholder="请填写场所联系人"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.contactInformation"
          center
          disabled
          label="联系方式:"
          placeholder="请填写联系方式"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.memorialTabletHolder"
          center
          label="供奉牌位人:"
          placeholder="请填写供奉牌位人"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.memorialTabletHolderPhone"
          center
          label-width="8em"
          label="供奉牌位人电话:"
          placeholder="请填写供奉牌位人电话"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.udCard"
          center
          required
          label="身份证号:"
          placeholder="请填写身份证号"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.nativePlace"
          readonly
          label="籍贯："
          placeholder="请选择籍贯地区"
          input-align="right"
          right-icon="arrow-down"
          @click="hs_nativePlace = true"
        />
        <van-popup v-model:show="hs_nativePlace" round position="bottom">
          <van-picker
            title="籍贯"
            :columns="nativePlace"
            :columns-field-names="customFieldName"
            @cancel="hs_nativePlace = false"
            @confirm="getnativePlace"
          />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.currentResidence"
          center
          readonly
          label="现居地："
          placeholder="请填写现居地"
          input-align="right"
          right-icon="arrow-down"
          @click="showPlace1 = true"
        />
        <van-popup v-model:show="showPlace1" round position="bottom">
          <van-picker
            title="现居地选择"
            :columns="options"
            :columns-field-names="customFieldName"
            @cancel="showPlace1 = false"
            @confirm="getPlace1"
          />
        </van-popup>
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.currentResidenceDel"
          center
          label="现居地详情:"
          placeholder="请填写现居地详情"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.relationship"
          center
          label-width="8em"
          label="与供奉牌位关系:"
          placeholder="请填写与供奉牌位关系"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.sacrificeExpenses"
          center
          label-width="10em"
          label="供奉费用（元/年）:"
          placeholder="请填写供奉费用"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.position"
          center
          label="牌位位置:"
          placeholder="请填写牌位位置"
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          v-model="dataitem.information"
          rows="2"
          autosize
          label-width="8em"
          label="被供奉者信息："
          type="textarea"
          maxlength="50"
          placeholder="请填写被供奉者信息"
          show-word-limit
          input-align="right"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field name="uploader" label-align="top" label="牌位照片:">
          <template #input>
            <van-uploader
              readonly
              v-model="fileList"
              :max-count="5"
              accept=""
              :preview-full-image="false"
              :before-delete="deleteRead"
              @click-upload="chooseImg"
            >
            </van-uploader>
          </template>
        </van-field>
      </van-cell-group>
      <div class="subbtn">
        <van-button type="primary" @click="submit">确认修改</van-button>
        <van-button @click="onClickLeft" type="default" hairline
          >取消</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
import { onMounted, ref } from "vue";
import $base from "@/utils/config";
import tools from "@/api/sys/tools";
import placePerson from "@/api/placePerson/placePerson";
import TabletServer from "@/api/tabletManage/TabletServer";
import PlaceRegister from "@/api/placeRegister/placeRegister";
export default {
  setup() {
    // 导航栏颜色
    const selectColor = ref(window.localStorage.getItem("MZ_COLOR"));
    //牌位数据
    let dataitem = ref({});
    //数据接收
    const router = useRouter();
    onMounted(() => {
      var id = JSON.parse(router.currentRoute.value.query.id);
      new TabletServer().queryById(id).then((res) => {
        dataitem.value = res;
        dataitem.value.pic.split("|").forEach((item) => {
          if (item.trim().length > 0) {
            fileImg.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("程序附件//", "程序附件/"),
            });
          }
        });
        let addressid = dataitem.value.siteName.id;
        new PlaceRegister().queryById(addressid).then((res) => {
          locationName.value = res.name;
        });
      });

      //籍贯接口
      new placePerson().nativePlace().then((res) => {
        nativePlace.value.push(...res);
        options.value.push(...res);
      });
    });
    // 所属场所
    const locationName = ref("");
    const checked = ref("");
    const sitelist = ref([]);
    let hs_site = ref(false);
    const getsite = (val) => {
      locationName.value = val.name;
      const json = Object.assign(dataitem.value, {
        siteName: { id: val.id, name: val.name },
        siteContact: val.contact,
        contactInformation: val.contactNumber,
      });
      dataitem.value = json;
      checked.value = val.id;
    };
    const loading = ref(false);
    const finished = ref(false);
    let index = 0;
    const onLoad = () => {
      loading.value = true;
      finished.value = false;
      // 异步更新数据
      new PlaceRegister()
        .religiousList({
          current: index + 1,
          size: 10,
        })
        .then(({ records, pages }) => {
          sitelist.value = sitelist.value.concat(records);
          // 加载状态结束
          loading.value = false;
          if (index + 1 >= pages) {
            finished.value = true;
          }
          index++;
        });
    };
    //籍贯
    const customFieldName = {
      text: "name",
      value: "id",
    };
    const options = ref([]);
    const nativePlace = ref([]);
    let hs_nativePlace = ref(false);
    const getnativePlace = ({ selectedOptions }) => {
      hs_nativePlace.value = false;
      let str = "";
      selectedOptions.forEach((item) => {
        if (dataitem.nativePlace) {
          str = dataitem.nativePlace;
        }
        str += item.name + "/";
      });
      dataitem.nativePlace = str;
      const json = Object.assign(dataitem.value, { nativePlace: str });
      dataitem.value = json;
    };
    //现居地
    let placeAddress = ref("");
    let showPlace1 = ref(false);
    const getPlace1 = ({ selectedOptions }) => {
      showPlace1.value = false;
      let str1 = "";
      selectedOptions.forEach((item) => {
        if (dataitem.currentResidence) {
          str1 = dataitem.currentResidence;
        }
        str1 += item.name + "/";
      });
      const json = Object.assign(dataitem.value, {
        currentResidence: str1,
      });
      dataitem.value = json;
    };
    //图片上传
    let fileList = ref([]);
    let fileImg = ref([]);
    const chooseImg = () => {
      xm.chooseFile({
        count: 1,
        name: "file",
        url:
          $base +
          `/sys/file/webupload/upload?uploadPath=placememorialtablets/placeMemorialTablets`,
        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;
        fileImg.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 (fileImg.value[index]) {
            let delurl = fileImg.value[index].url;
            new tools().uploadFiledelete("", delurl).then(({ data }) => {});
            fileImg.value.splice(index, 1);
          }
        }
      }
    };
    //返回
    const onClickLeft = () => {
      history.back();
    };
    //数据提交
    const submit = () => {
      dataitem.value.pic = fileImg.value.map((option) => option.id).join("|");
      new TabletServer().save(dataitem.value).then((res) => {
        if (res.status == 200) {
          xm.showToast({
            message: "牌位信息修改成功",
          });
          // router.push({
          //   path: "/placeTablet",
          // });
        }else{
          xm.showToast({
            message: "牌位信息修改失败",
          });
          console.log(res);
        }
      });
    };
    return {
      onClickLeft,
      dataitem,
      selectColor,
      //所属场所
      locationName,
      checked,
      hs_site,
      getsite,
      sitelist,
      loading,
      finished,
      onLoad,
      //籍贯
      nativePlace,
      hs_nativePlace,
      getnativePlace,
      customFieldName,
      //现居地
      options,
      placeAddress,
      showPlace1,
      getPlace1,
      //图片上传
      fileList,
      chooseImg,
      //图片删除
      deleteRead,
      //数据提交
      submit,
    };
  },
};
</script>

<style lang="less">
.dialog {
  width: 100%;
  height: 400px;
  overflow: auto;
}
</style>