<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.trim="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='newAgencyId'
                        label-width="150px">
            <el-cascader ref="myCascader"
                         v-model.trim="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="newNeighborHoodId">

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

              <el-select v-model.trim="dataForm.newNeighborHoodId"
                         placeholder="请选择小区"
                         clearable
                         class="item_width_1"
                         @change="handleChangeCommunity">
                <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.newBuildingId"
                         placeholder="请选择楼号"
                         clearable
                         class="item_width_1 margin_left10"
                         @change="handleChangeBuilding">
                <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.newBuildingUnitId"
                         placeholder="请选择单元"
                         clearable
                         class="item_width_1 margin_left10"
                         @change="handleChangeUnit">
                <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.newHouseId"
                         placeholder="请选择房号"
                         clearable
                         class="item_width_1 margin_left10">
                <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>
        <el-form-item label="备注"
                      prop="remark"
                      label-width="150px">
          <el-input type="textarea"
                    :autosize="{ minRows: 4, maxRows: 7}"
                    :rows="5"
                    resize="none"
                    style="width:600px"
                    placeholder='请输入备注'
                    v-model.trim="dataForm.remark">
          </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】	
        newAgencyId: '',//调动到的组织Id		
        newGridId: '',//调动到的网格Id		
        newNeighborHoodId: '',//调动到的小区ID			
        newBuildingId: '',//调动到的楼宇Id			
        newBuildingUnitId: '',//调动到的单元Id			
        newHouseId: '', //调动到的房屋Id		
        transferTime: '', //调动时间【日期类型】			
        remark: '' //备注		
      },

      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 () {

  },

  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

      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.newAgencyId = this.selGrid.pid
      this.dataForm.newGridId = this.selGrid.agencyId
      this.loadCommunityList()
      this.dataForm.newNeighborHoodId = ''//调动到的小区ID			
      this.dataForm.newBuildingId = ''//调动到的楼宇Id			
      this.dataForm.newBuildingUnitId = ''//调动到的单元Id			
      this.dataForm.newHouseId = '' //调动到的房屋Id		

    },

    async loadCommunityList () {
      const url = '/actual/base/communityQuarters/listQuartersOptions'

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

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

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

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

    async handleChangeCommunity () {

      const url = '/actual/base/communityBuilding/buildingoption'

      let params = {
        quartersId: this.dataForm.newNeighborHoodId
      }

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

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

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

    async handleChangeBuilding () {

      const url = '/actual/base/communityBuildingUnit/unitoption'

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

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

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


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

    async handleChangeUnit () {

      const url = '/actual/base/communityHouse/houseoption'

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

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

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

    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.newBuildingId) {
              this.$message.warning('楼栋')
              return false
            }
            if (!this.dataForm.newBuildingUnitId) {
              this.$message.warning('请选择单元')
              return false
            }
            if (!this.dataForm.newHouseId) {
              this.$message.warning('请选择房间')
              return false
            }
          }
          this.saveForm()
        }

      })
    },

    async saveForm () {
      const url = '/epmetuser/icusertransferrecord/add'
      let noData = new Date()
      noData = util.dateFormatter(noData, 'time')
      this.dataForm.transferTime = noData

      const { data, code, msg } = await requestPost(url, 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】	
        newAgencyId: '',//调动到的组织Id		
        newGridId: '',//调动到的网格Id		
        newNeighborHoodId: '',//调动到的小区ID			
        newBuildingId: '',//调动到的楼宇Id			
        newBuildingUnitId: '',//调动到的单元Id			
        newHouseId: '', //调动到的房屋Id		
        transferTime: '', //调动时间【日期类型】			
        remark: '' //备注		
      }

      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()
      }
    }
  },
  computed: {
    dataRule () {
      return {
        type: [
          { required: true, message: '操作类型不能为空', trigger: 'blur' },
        ],
        newAgencyId: [
          { required: true, message: '所选组织不能为空', trigger: 'blur' }
        ],
        newNeighborHoodId: [
          { required: true, message: '所属家庭不能为空', trigger: 'blur' }
        ],

      }
    },

  },
  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>
