<template>
  <div class="bg-caiji">
    <div class="title">
      居民信息填报
    </div>
    <div class="main">

      <div class="content">

        <mt-cell title="所属社区">

          <span style="margin-right:20px">{{shequName}}</span>
        </mt-cell>
        <div class="line"></div>

        <div v-if="formData.origin === 'internal'">
          <div @click="handelSel('community')">
            <mt-cell title="小区"
                     is-link>
              <span class="picker_content"
                    v-if="selVillage">{{selVillage.label}}</span>
              <span v-else>请选择</span>
            </mt-cell>
          </div>
          <div class="line"></div>

          <div @click="handelSel('building')">
            <mt-cell title="楼宇"
                     is-link>
              <span class="picker_content"
                    v-if="selBuild">{{selBuild.label}}</span>
              <span v-else>请选择</span>
            </mt-cell>
          </div>
          <div class="line"></div>

          <div @click="handelSel('unit')">
            <mt-cell title="单元"
                     is-link>
              <span class="picker_content"
                    v-if="selUnit">{{selUnit.label}}</span>
              <span v-else>请选择</span>
            </mt-cell>
          </div>
          <div class="line"></div>

          <mt-field v-if="selUnit && selUnit.value==='else'"
                    class="my-field"
                    :disableClear="true"
                    label="单元号"
                    placeholder="请输入"
                    v-model="unitContent"></mt-field>
          <div class="line"></div>

          <div v-if="!selUnit || selUnit.value!=='else'"
               @click="handelSel('room')">
            <mt-cell title="房屋"
                     is-link>
              <span class="picker_content"
                    v-if="selHome">{{selHome.label}}</span>
              <span v-else>请选择</span>
            </mt-cell>
            <div class="line"></div>
          </div>

          <mt-field v-if="(selUnit&&selUnit.value==='else')||(selHome&&selHome.value==='else')"
                    class="my-field"
                    :disableClear="true"
                    label="房屋"
                    placeholder="请输入"
                    v-model="homeContent"></mt-field>

        </div>
        <div v-if="formData.origin === 'external'">
          <mt-field class="my-field"
                    :disableClear="true"
                    label="详细地址"
                    placeholder="xx小区(号)x号楼x单元x户"
                    v-model="formData.address"></mt-field>
          <div class="line"></div>
        </div>

      </div>
      <div class="content content1">
        <div @click="handelSel('roomType')">
          <mt-cell title="房屋类型"
                   is-link>
            <span class="picker_content"
                  v-if="selHomeType">{{selHomeType.label}}</span>
            <span v-else>请选择</span>
          </mt-cell>
        </div>
        <div class="line"></div>

        <mt-field class="my-field"
                  label="户主姓名"
                  :disableClear="true"
                  placeholder="请输入"
                  v-model="formData.houseHolderName"></mt-field>
        <div class="line"></div>

        <div @click="handelSel('totalResi')">
          <mt-cell :title="'居住成员人数'"
                   is-link>
            <span class="picker_content"
                  v-if="selTotalResi">{{selTotalResi.label}}</span>
            <span v-else>请选择</span>
          </mt-cell>
        </div>

        <!-- <mt-field class="my-field"
                  label="居住成员人数"
                  :disableClear="true"
                  placeholder="请输入"
                  type="number"
                  @blur.native.capture="bluraa"
                  v-model="formData.totalResi"></mt-field>
        <div class="line"></div> -->

      </div>

      <div v-for="(item,index) in memberList"
           :key="index">
        <div class="content content1">
          <div class="member_title">{{'成员'+(index+1)}}</div>
          <mt-field class="my-field"
                    :disableClear="true"
                    :label="'姓名'"
                    placeholder="请输入"
                    v-model="item.name"></mt-field>
          <div class="line"></div>
          <mt-field class="my-field"
                    :disableClear="true"
                    :label="'身份证'"
                    placeholder="请输入"
                    v-model="item.idNum"></mt-field>
          <div class="line"></div>
          <mt-field class="my-field"
                    :disableClear="true"
                    :label="'手机号'"
                    placeholder="请输入"
                    type="tel"
                    v-model="item.mobile"></mt-field>
          <div class="line"></div>

          <div @click="handelSel('detNum',index)">
            <mt-cell :title="'参加核酸检测次数'"
                     is-link>
              <span class="picker_content"
                    v-if="item.selDetNum.value">{{item.selDetNum.label}}</span>
              <span v-else>请选择</span>
            </mt-cell>
          </div>
          <div class="line"></div>

          <div @click="handelSel('detCondition',index)">
            <mt-cell :title="'新冠疫苗接种情况'"
                     is-link>
              <span class="picker_content"
                    v-if="item.selDetCondition.value">{{item.selDetCondition.label}}</span>
              <span v-else>请选择</span>
            </mt-cell>
          </div>
          <div class="line"></div>
        </div>

      </div>

    </div>

    <div class="div-btn">
      <mt-button @click="handleSubmit"
                 type="primary"
                 class="btn"
                 :disabled="btnDisabled"
                 size="small">提交</mt-button>
    </div>

    <mt-popup v-model="popupVisible"
              popup-transition="popup-fade"
              closeOnClickModal="true"
              position="bottom">
      <mt-picker :slots="popupSlots"
                 value-key="label"
                 @change="onPickerChange"
                 showToolbar>
        <div class="picker-toolbar-title">
          <div class="usi-btn-cancel"
               @click="popupVisible = !popupVisible">取消</div>
          <div class="">请选择</div>
          <div class="usi-btn-sure"
               @click="popupOk()">确定</div>
        </div>
      </mt-picker>
    </mt-popup>

  </div>
</template>
<script>


import { requestPost } from "@/js/dai/request";
import { Toast } from "mint-ui";
import { MessageBox } from 'mint-ui';
import { Loading } from 'element-ui' // 引入Loading服务

let loading // 加载动画
export default {
  data () {
    return {
      btnDisabled: false,
      popupVisible: false,

      //二维码带来数据
      shequId: '',//社区id   6e511da6816e53af4cda952365a26eb9  德兴路  1202807601961984002
      shequName: '',//社区名称
      customerId: '',//客户id  45687aa479955f9d06204d415238f7cc

      communityList: [],
      buildingList: [],
      unitList: [],
      roomList: [],
      selType: 'community',//弹出框所显示的数据类型：community、building、unit、room
      pickerData: [],

      selObj: {},
      selVillage: null,
      selBuild: null,
      selUnit: null,
      selHome: null,
      selHomeType: null,
      selTotalResi: {
        label: '4人',
        value: 4
      },

      unitContent: '',
      homeContent: '',////选择其他时，输入的值
      formData: {
        origin: '',//兴德路社区：internal;其他社区：external	
        villageId: '',//小区id；外部不显示此组件；如果是内部必填。用户选择其他，可以自己输入，前端把输入的内容放在这个字段即可	
        buildId: '',//楼栋id；外部不显示此组件；如果是内部必填，用户选择其他，可以自己输入，前端把输入的内容放在这个字段即可	
        unitId: '',//单元id；外部不显示磁组件。如果是内部必填。用户可以选择其他，自己输入，前端把输入的内容放在这个字段即可	
        homeId: '',//房屋id；外部不展示此组件。如果是内部必填。用户选择其他，可以自己输入，前端把输入的内容放在这个字段即可	
        address: '',//外部：用户自己输入；内部：把小区名楼栋名单元名房屋名拼接起来。例如：绿地望海领域10号楼一单元101	
        houseType: '',//1自由0租住	
        houseHolderName: '',//户主姓名	
        totalResi: 4,//居住成员人数	
        customerId: '',//customerId

      },
      showMessagsBox: false,//是否显示人员未填写提示弹出框

      selMemberIndex: null,

      memberList: [
        {
          name: '',
          mobile: '',
          idNum: '',
          customerId: '',
          heSuanCount: 0,
          ymjz: '',
          selDetNum: {},
          selDetCondition: {}
        },

      ],

      roomTypeList: [
        {
          value: '1',
          label: '自有'
        },
        {
          value: '0',
          label: '租住'
        },
      ],
      totalResiList: [],
      detNumList: [],//参加核酸次数list
      detConditionList: [//参加核酸类型list
        {
          // label: '已全程接种（包含加强针或序贯）',
          label: '已全程接种',
          value: '1'
        },
        {
          label: '未全程接种',
          value: '2'
        },
        {
          label: '未接种',
          value: '0'
        },
      ],


      popupSlots: [//问题类型弹框数据
        {
          values: []
        }
      ],

    }
  },
  components: {},
  computed: {

  },
  created () { },
  mounted () {
    console.log(this.$route)

    this.shequId = this.$route.params.id
    this.customerId = this.$route.query.customerId
    this.shequName = this.$route.query.name

    let envShow = process.env.VUE_APP_NODE_ENV
    console.log('环境', envShow)

    let internalShequId = ['1202807601961984002', '6e511da6816e53af4cda952365a26eb9',]
    // let internalShequId = ['1202807601961984002',]
    // if (envShow === 'dev' || envShow === 'prod:sit') { // 开发环境
    //   internalShequId = null
    // } else if (envShow === 'prod:uat') { // 体验
    //   internalShequId = '6e511da6816e53af4cda952365a26eb9'
    // } else if (envShow === 'prod') { // 生产
    //   internalShequId = '1202807601961984002'
    // }

    this.formData.customerId = this.customerId
    if (internalShequId.indexOf(this.shequId) > -1) {
      this.formData.origin = 'internal'
    } else {
      this.formData.origin = 'external'
    }
    this.loadVillage()
    this.detNumList = []
    for (let i = 1; i < 11; i++) {
      let obj = {
        value: i + '',
        label: i + '次',
      }
      this.detNumList.push(obj)
    }

    for (let i = 1; i < 9; i++) {
      let obj = {
        value: i,
        label: i + '人',
      }
      this.totalResiList.push(obj)
    }

    this.bluraa()
  },

  methods: {


    //根据社区id获取小区列表
    async loadVillage () {
      const url = "/gov/org/icneighborhood/open/list"

      let params = {
        agencyId: this.shequId,
        isPage: false
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        data.list.forEach(element => {
          element.label = element.neighborHoodName
          element.value = element.id
        });
        this.communityList = data.list
        let obj = {
          values: this.communityList
        }

        this.popupSlots = []
        this.popupSlots.push(obj)
      } else {
        Toast({
          message: msg,
          duration: 3000
        });
      }
    },
    //获取楼宇列表
    async loadBuild () {
      const url = "/gov/org/icbuilding/buildingoption"
      let params = {

        neighborHoodId: this.selVillage.value
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        // data.forEach(element => {
        //   element.label = element.buildingName
        //   element.value = element.buildingId
        // });
        this.buildingList = data
        let obj = {
          values: this.buildingList
        }

        this.popupSlots = []
        this.popupSlots.push(obj)
      } else {
        Toast({
          message: msg,
          duration: 3000
        });
      }
    },
    //获取单元列表
    async loadUnit () {
      const url = '/gov/org/icbuildingunit/unitoption'

      let params = {
        buildingId: this.selBuild.value
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        // data.forEach(element => {
        //   element.label = element.unitName
        //   element.value = element.id
        // });
        this.unitList = data
        this.unitList.push({
          label: '其他',
          value: 'else'
        })
        let obj = {
          values: this.unitList
        }

        this.popupSlots = []
        this.popupSlots.push(obj)
      } else {
        Toast({
          message: msg,
          duration: 3000
        });
      }
    },
    //获取房间列表
    async loadHome () {
      const url = "/gov/org/ichouse/houseoption"

      let params = {
        buildingId: this.selBuild.value,
        unitId: this.selUnit.value
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        // data.forEach(element => {
        //   element.label = element.unitName
        //   element.value = element.id
        // });
        this.roomList = data
        this.roomList.push({
          label: '其他',
          value: 'else'
        })
        let obj = {
          values: this.roomList
        }

        this.popupSlots = []
        this.popupSlots.push(obj)
      } else {
        Toast({
          message: msg,
          duration: 3000
        });
      }
    },

    handelSel (selType, index) {
      this.selType = selType
      if (selType === 'community') {
        this.pickerData = this.communityList

      }
      if (selType === 'building') {
        if (!this.selVillage) {
          Toast({
            message: '请先选择小区',
            duration: 3000
          });
          return false
        } else {
          this.pickerData = this.buildingList
        }


      }
      if (selType === 'unit') {
        if (!this.selBuild) {
          Toast({
            message: '请先选择楼宇',
            duration: 3000
          });
          return false
        } else {
          this.pickerData = this.unitList
        }

      }
      if (selType === 'room') {
        if (!this.selUnit) {
          Toast({
            message: '请先选择单元',
            duration: 3000
          });
          return false
        } else {
          this.pickerData = this.roomList
        }

      }

      if (selType === 'totalResi') {
        this.pickerData = this.totalResiList
      }
      if (selType === 'roomType') {
        this.pickerData = this.roomTypeList
      }
      if (selType === 'detNum') {
        this.selMemberIndex = index
        this.pickerData = this.detNumList
      }
      if (selType === 'detCondition') {
        this.selMemberIndex = index
        this.pickerData = this.detConditionList
      }

      let obj = {
        values: this.pickerData
      }

      this.popupSlots = []
      this.popupSlots.push(obj)
      this.popupVisible = !this.popupVisible
    },

    async handleSubmit () {
      let message = this.validataFormData()


      if (message) {
        if (this.showMessagsBox) {
          MessageBox.confirm(message).then(action => {
            this.submit()
          });
        } else {
          Toast({
            message: message,
            duration: 3000
          });
        }
      } else {
        this.submit()
      }


    },
    async submit () {


      if (this.formData.origin === 'internal') {

        this.formData.villageId = this.selVillage.value
        this.formData.buildId = this.selBuild.value
        if (this.selUnit.value === 'else') {
          this.formData.unitId = this.unitContent
          this.formData.homeId = this.homeContent//没有选择房屋，不存在这个对象，直接赋值
        } else {
          this.formData.unitId = this.selUnit.value
          this.unitContent = this.selUnit.label

          if (this.selHome.value === 'else') {
            this.formData.homeId = this.homeContent
          } else {
            this.formData.homeId = this.selHome.value
            this.homeContent = this.selHome.label
          }
        }


        this.formData.address = this.selVillage.label + this.selBuild.label + this.unitContent + this.homeContent
      }

      this.formData.houseType = this.selHomeType.value

      this.memberList.forEach(element => {
        element.customerId = this.customerId
        if (element.selDetNum && element.selDetNum.value) {
          element.heSuanCount = element.selDetNum.value
        }
        if (element.selDetCondition && element.selDetCondition.value) {
          element.ymjz = element.selDetCondition.value
        }

      });
      this.formData.memberList = this.memberList
      console.log(this.formData)
      this.btnDisabled = true
      this.startLoading()
      const url = "/epmetuser/icresicollect/save"

      const { data, code, msg } = await requestPost(url, this.formData)
      this.endLoading()
      this.btnDisabled = false
      if (code === 0) {

        this.$router.replace({ name: 'caijisuccess' })
        // Toast({
        //   message: '提交成功',
        //   duration: 3000
        // });

      } else {
        Toast({
          message: msg,
          duration: 3000
        });

      }
    },



    //必填验证
    validataFormData () {

      let aletMessage = ''
      this.showMessagsBox = false
      if (this.formData.origin === 'internal') {//内部
        if (!this.selVillage) {
          aletMessage = '请选择小区'

          return aletMessage
        }
        if (!this.selBuild) {
          aletMessage = '请选择楼栋'
          return aletMessage
        }

        if (!this.selUnit) {//没有选择单元
          aletMessage = '请选择单元'
          return aletMessage

        } else {//选择了单元
          if (this.selUnit.value === 'else') {//单元选择了其他
            if (!this.unitContent) {
              aletMessage = '请填写单元号'
              return aletMessage
            }

            if (!this.homeContent) {//房屋必须填写内容
              aletMessage = '请填写房屋'
              return aletMessage
            }

          } else {//单元没有选择其他
            if (!this.selHome) {
              aletMessage = '请选择房屋'
              return aletMessage

            } else if (this.selHome.value === 'else' && !this.homeContent) {
              aletMessage = '请填写房屋'
              return aletMessage
            }
          }

        }


      } else {
        if (!this.formData.address) {
          aletMessage = '请填写地址'
          return aletMessage
        }
      }

      if (!this.selHomeType) {
        aletMessage = '请选择房屋类型'
        return aletMessage
      }
      if (!this.formData.houseHolderName) {
        aletMessage = '请填写户主姓名'
        return aletMessage
      }
      let member1 = this.memberList[0]


      if (!member1.name || !member1.mobile || !member1.idNum || !member1.selDetNum.value || !member1.selDetCondition.value) {
        aletMessage = '请完整填写用户1信息'
        return aletMessage
      }


      for (let i = 1; i < this.memberList.length; i++) {
        let item = this.memberList[i]

        if (item.name || item.mobile || item.idNum || item.selDetNum.value || item.selDetCondition.value) {//填写了信息的，必须填写姓名身份证
          if (!item.name || !item.idNum) {
            aletMessage = '请完整填写用户' + (i + 1) + '的姓名和身份证信息'
            return aletMessage
          }
        } else {
          aletMessage = '用户' + (i + 1) + '的信息没有填写，是否继续'
          this.showMessagsBox = true
          return aletMessage

        }

      }


    },

    popupOk () {
      if (this.selType === 'community') {
        this.selVillage = this.selObj
        this.selBuild = null
        this.selUnit = null
        this.selHome = null
        this.formData.unitContent = ''
        this.formData.homeContent = ''
        this.loadBuild()

      }
      if (this.selType === 'building') {
        this.selBuild = this.selObj
        this.formData.buildContent = this.selObj.label
        this.formData.buildId = this.selObj.value

        this.selUnit = null
        this.selHome = null
        this.formData.unitContent = ''
        this.formData.homeContent = ''
        this.loadUnit()

      }
      if (this.selType === 'unit') {
        this.selUnit = this.selObj

        this.selHome = null
        this.unitContent = ''
        this.homeContent = ''

        this.loadHome()

      }
      if (this.selType === 'room') {
        this.selHome = this.selObj
        this.homeContent = ''
      }

      if (this.selType === 'totalResi') {
        this.selTotalResi = this.selObj
        this.formData.totalResi = this.selObj.value
        this.bluraa()
      }

      if (this.selType === 'roomType') {
        this.selHomeType = this.selObj
      }

      if (this.selType === 'detNum') {

        let change = this.memberList[this.selMemberIndex]
        change.selDetNum = this.selObj
        this.$set(this.memberList, this.selMemberIndex, change)

      }
      if (this.selType === 'detCondition') {
        let change = this.memberList[this.selMemberIndex]
        change.selDetCondition = this.selObj
        this.$set(this.memberList, this.selMemberIndex, change)
      }

      this.popupVisible = false

    },

    bluraa () {
      let objTemp = {
        name: '',
        mobile: '',
        idNum: '',
        heSuanCount: 0,
        ymjz: '',
        selDetNum: {},
        customerId: '',
        selDetCondition: {}
      }

      if (this.memberList.length > this.formData.totalResi) {//已有成员数量比设置的数量大，删除多余
        let differ = this.memberList.length - this.formData.totalResi
        this.memberList.splice(this.formData.totalResi, differ)
      } else if (this.memberList.length < this.formData.totalResi) {////已有成员数量比设置的数量小，补充空对象
        let differ = this.formData.totalResi - this.memberList.length

        for (let i = 0; i < differ; i++) {
          let temp = JSON.parse(JSON.stringify(objTemp))
          this.memberList.push(temp)
        }
      }


      console.log(this.memberList)
    },

    onPickerChange (picker, values) {

      this.selObj = values[0]

    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }


  }
}
</script>

<style lang="scss" scoped >
@import "@/assets/scss/pages/caiji.scss";

.my-field /deep/ .mint-field-core {
  text-align: right;
  margin-right: 20px;
}

/deep/ .mint-popup-bottom {
  width: 100vw;
}

.picker-toolbar-title {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  background-color: #eee;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  .usi-btn-cancel,
  .usi-btn-sure {
    color: #26a2ff;
    font-size: 16px;
  }
}
</style>
