<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="false"
               :model="dataForm"
               :rules="dataRule"
               class="form">

        <el-form-item label="当前组织"
                      label-width="150px"
                      style="display: block">
          <span>{{ gridName }}</span>
        </el-form-item>

        <el-form-item label="迁出类型"
                      prop="type"
                      label-width="150px"
                      style="display: block">
          <el-radio-group v-model="dataForm.type">

            <el-radio :label="'in'">{{'迁往'+rootAgency.organizationName+'内其他区域'}}</el-radio>
            <el-radio :label="'out'">其他</el-radio>

          </el-radio-group>
        </el-form-item>

        <div v-if="dataForm.type==='in'">
          <el-form-item label="迁出至"
                        prop='agencyId'
                        label-width="150px">
            <el-cascader ref="myCascader"
                         v-model="agencyIdArray"
                         style="width:480px"
                         :key="iscascaderShow"
                         :options="casOptions"
                         :props="optionProps"
                         @change="handleChangeAgency"
                         clearable></el-cascader>
          </el-form-item>

          <el-form-item label="所属家庭"
                        label-width="150px"
                        prop="villageId">

            <div class="resi-cell-col">

              <el-select v-model.trim="dataForm.villageId"
                         placeholder="请选择小区"
                         clearable
                         class="item_width_1"
                         @change="handleChangeCommunity($event)">
                <el-option v-for="item in communityList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>

              <el-select v-model.trim="dataForm.buildId"
                         placeholder="请选择楼号"
                         clearable
                         class="item_width_1 margin_left10"
                         @change="handleChangeBuilding($event)">
                <el-option v-for="item in buildingList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>

              <el-select v-model.trim="dataForm.unitId"
                         placeholder="请选择单元"
                         clearable
                         class="item_width_1 margin_left10"
                         @change="handleChangeUnit($event)">
                <el-option v-for="item in unitList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>

              <el-select v-model.trim="dataForm.homeId"
                         placeholder="请选择房号"
                         clearable
                         class="item_width_1 margin_left10"
                         @change="handleChangeHome($event)">
                <el-option v-for="item in roomList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>

            </div>

          </el-form-item>

        </div>
        <div v-if="dataForm.type==='out'">
          <el-form-item label="外迁详细地址"
                        prop="address"
                        label-width="150px">
            <el-input type="textarea"
                      :autosize="{ minRows: 2, maxRows: 7}"
                      :rows="5"
                      resize="none"
                      style="width:600px"
                      placeholder='请输入外迁详细地址'
                      v-model="dataForm.address">
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="迁出原因"
                      prop="reason"
                      label-width="150px">
          <el-input type="textarea"
                    :autosize="{ minRows: 4, maxRows: 7}"
                    :rows="5"
                    resize="none"
                    style="width:600px"
                    placeholder='请输入迁出原因'
                    v-model="dataForm.reason">
          </el-input>
        </el-form-item>
      </el-form>

    </div>
    <!-- <div class="div_btn">
      <el-button @click="handleCancle">取 消</el-button>
      <el-button type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div> -->
    <div class="resi-btns">
      <el-button size="small"
                 @click="handleCancle">取消</el-button>
      <el-button type="primary"
                 size="small"
                 :loading="btnDisable"
                 @click="handleComfirm">提交</el-button>
    </div>
  </div>
</template>

<script>
import util from '@js/util.js';
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'

let loading // 加载动画
export default {
  data () {
    return {

      btnDisable: false,
      communityList: [],
      buildingList: [],
      unitList: [],
      roomList: [],

      dataForm: {
        icUserId: '', // 被调动人ID
        type: 'in',//操作类型【客户外out,客户内in】
        agencyId: '',//调动到的组织Id
        gridId: '',//调动到的网格Id
        gridName: '',
        villageId: '',//调动到的小区ID
        villageName: '',
        buildId: '',//调动到的楼宇Id
        buildName: '',
        unitId: '',//调动到的单元Id
        unitName: '',
        homeId: '', //调动到的房屋Id
        homeName: '',
        transferTime: '', //调动时间【日期类型】
        reason: '', //备注
        customerId: '',
        oldHome: '',
        oldDept: '',
        oldAddress: '',
        ownerName: '',
        name: '',
        gender: '',
        age: '',
        address: ''
      },

      customerId: '',//客户id
      userId: '',//操作人员id
      gridName: '',
      rootAgency: {},

      casOptions: [],
      agencyIdArray: [],
      customerList: [],
      iscascaderShow: 0,

      optionProps: {
        multiple: false,
        value: 'agencyId',
        label: 'agencyName',
        children: 'subAgencyList',
        // checkStrictly: true
      },

      selGrid: {},


    }
  },
  components: {},
  mounted () {

  },
    computed: {
        dataRule () {
            return {
                type: [
                    { required: true, message: '操作类型不能为空', trigger: 'blur' },
                ],
                agencyId: [
                    { required: true, message: '所选组织不能为空', trigger: 'blur' }
                ],
                villageId: [
                    { required: true, message: '所属家庭不能为空', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '外迁详细地址不能为空', trigger: 'blur' }
                ],

            }
        },

    },
  methods: {
    async initForm (row) {

      this.customerId = localStorage.getItem("customerId");

      this.$refs.ref_form.resetFields();

      // this.icUserId = row.icResiUserId
      this.gridName = row.GRID_ID
      this.dataForm.icUserId = row.icResiUserId

      // 添加参数
        if(row.DOOR_NAME !== null && row.DOOR_NAME !== '' && row.DOOR_NAME !== undefined){
            this.dataForm.oldHome = row.DOOR_NAME
        }
        this.dataForm.customerId = this.customerId
        this.dataForm.idCard = row.ID_CARD
        this.dataForm.mobile = row.MOBILE

        this.dataForm.oldDept = row.GRID_ID
        this.dataForm.oldAddress = row.HOME_ID
        this.dataForm.ownerName = row.NAME

        this.dataForm.name = row.NAME
        this.dataForm.gender = row.GENDER
        this.dataForm.age = ''


      await this.loadRootAgency()
      await this.getAgencylist()

    },

    //根据人员id获取根组织信息
    async loadRootAgency () {

      await this.$http.post('/gov/org/agency/customerrootagency/' + this.customerId).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }

        if (res.data) {
          this.rootAgency = res.data
        }
      }).catch(() => { })

    },

    async getAgencylist () {

      const url = '/gov/org/customeragency/rootagencygridtree'


      const params = {
        agencyId: this.rootAgency.id
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        ++this.iscascaderShow
        this.casOptions = []
        this.agencyIdArray.length = []

        if (data) {
          let treeData = [data]
          this.resolveAgencyTree(treeData)
          this.casOptions.push(data)
        }

      } else {
        this.$message.error(msg)
      }
    },

    resolveAgencyTree (treeData) {
      treeData.forEach(element => {
        if (!element.subAgencyList || element.subAgencyList.length === 0) {//不存在下级，且level=grid的是true

          if (element.level === 'grid') {
            element.disabled = false
          } else {
            element.disabled = true
          }

        } else {
          this.resolveAgencyTree(element.subAgencyList)
        }
      });
    },

    handleChangeAgency () {
      console.log(this.$refs["myCascader"].getCheckedNodes()[0].data)
      this.selGrid = this.$refs["myCascader"].getCheckedNodes()[0].data
      this.dataForm.agencyId = this.selGrid.pid
      this.dataForm.gridId = this.selGrid.agencyId
      this.dataForm.gridName = this.selGrid.agencyName
      this.loadCommunityList()
      this.dataForm.villageId = ''//调动到的小区ID
      this.dataForm.villageName = ''
      this.dataForm.buildId = ''//调动到的楼宇Id
      this.dataForm.buildName = ''
      this.dataForm.unitId = ''//调动到的单元Id
      this.dataForm.unitName = ''
      this.dataForm.homeId = '' //调动到的房屋Id
      this.dataForm.homeName = ''

    },

    async loadCommunityList () {
      const url = '/gov/org/icneighborhood/neighborhoodoption'

      let params = {
        gridId: this.dataForm.gridId,
        agencyId: this.dataForm.agencyId
      }

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

      if (code === 0) {
        this.communityList = []
        this.communityList = [...data]

      } else {
        this.$message.error(msg)
      }
    },

    async handleChangeCommunity (id) {
        // 小区
        this.communityList.find((item) => {
            if (item.value === id) {
                this.dataForm.villageName = item.label
            }
        })

      const url = '/gov/org/icbuilding/buildingoption'

      let params = {
        neighborHoodId: this.dataForm.villageId
      }

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

      if (code === 0) {
        this.buildingList = []
        this.buildingList = [...data]
        this.dataForm.buildId = ''//调动到的楼宇Id
        this.dataForm.unitId = ''//调动到的单元Id
        this.dataForm.homeId = '' //调动到的房屋Id

      } else {
        this.$message.error(msg)
      }
    },

    async handleChangeBuilding (id) {

        // 楼号
        this.buildingList.find((item) => {
            if (item.value === id) {
                this.dataForm.buildName = item.label
            }
        })

      const url = '/gov/org/icbuildingunit/unitoption'

      let params = {
        buildingId: this.dataForm.buildId
      }

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

      if (code === 0) {
        this.unitList = []
        this.unitList = [...data]
        this.dataForm.unitId = ''//调动到的单元Id
        this.dataForm.homeId = '' //调动到的房屋Id


      } else {
        this.$message.error(msg)
      }
    },

    async handleChangeUnit (id) {
        // 单元号
        this.unitList.find((item) => {
            if (item.value === id) {
                this.dataForm.unitName = item.label
            }
        })

      const url = '/gov/org/ichouse/houseoption'

      let params = {
        unitId: this.dataForm.unitId
      }

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

      if (code === 0) {
        this.roomList = []
        this.roomList = [...data]
        this.dataForm.homeId = '' //调动到的房屋Id
      } else {
        this.$message.error(msg)
      }
    },

      async handleChangeHome (id) {
          // 房屋号
          this.roomList.find((item) => {
              if (item.value === id) {
                  this.dataForm.homeName = item.label
              }
          })
      },

    async handleComfirm () {
      this.btnDisable = true
      setTimeout(() => {
        this.btnDisable = false
      }, 2000)


      this.$refs['ref_form'].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj)

        } else {
          if (this.dataForm.type === 'in') {


            if (!this.dataForm.buildId) {
              this.$message.warning('楼栋')
              return false
            }
            if (!this.dataForm.unitId) {
              this.$message.warning('请选择单元')
              return false
            }
            if (!this.dataForm.homeId) {
              this.$message.warning('请选择房间')
              return false
            }
          }
          this.saveForm()
        }

      })
    },

    async saveForm () {
      const url = '/pli/power/changeRelocation/saveOutOfInfo'
      let noData = new Date()
      noData = util.dateFormatter(noData, 'time')
      this.dataForm.transferTime = noData

      const { data, code, msg } = await requestPost(url, this.dataForm)
        console.log('----------------')
        console.log(this.dataForm)

      if (code === 0) {
        this.$message.success('调动成功')
        this.handleCancle()
      } else {
        this.$message.error(msg)
      }
    },

    handleCancle () {
      this.resetData()
      this.$emit('dialogCancle')

    },

    resetData () {
      this.dataForm = {
        icUserId: '', // 被调动人ID
        type: 'in',//操作类型【客户外out,客户内in】
        agencyId: '',//调动到的组织Id
        gridId: '',//调动到的网格Id
        villageId: '',//调动到的小区ID
        buildId: '',//调动到的楼宇Id
        unitId: '',//调动到的单元Id
        homeId: '', //调动到的房屋Id
        transferTime: '', //调动时间【日期类型】
        reason: '' //备注
      }

      this.customerId = ''//客户id
      this.userId = ''//操作人员id
      this.gridName = ''
      this.rootAgency = {}

      this.selGrid = {}

    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  props: {}
}
</script>
<style lang="scss" scoped>
.item_width_1 {
  width: 150px;
}
.item_width_2 {
  width: 400px;
}
.item_width_3 {
  margin-left: 10px;
  width: 200px;
}

.div_btn {
  display: flex;
  justify-content: flex-end;
}
.resi-cell-col {
  width: 750px;
  display: flex;
  justify-content: flex-start;
}

.margin_left10 {
  margin-left: 10px;
}
</style>
<style>
.el-dialog__body {
  padding: 0 10px 20px !important;
}
</style>
