<template>
  <div class="main">
    <div></div>
    <el-form
      ref="ruleForm"
      :model="formData"
      label-width="100px"
      :rules="formRules"
    >
      <div class="formContent">
        <div class="formContent-item">
          <div class="formContent-item_title">基础信息</div>
          <div class="formContent-formList">
            <div>
              <el-form-item
                label="姓名"
                prop="name"
              >
                <el-input
                  v-model="formData.name"
                  placeholder="请输入姓名"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="手机号"
                prop="phone"
              >
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入手机号"
                  maxlength="11"
                ></el-input>
              </el-form-item>
              <el-form-item label="人员编号">
                <el-input
                  v-model="formData.personnelNumber"
                  placeholder="请输入人员编号"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="性别"
                required
              >
                <el-radio
                  v-model="formData.sex"
                  :label="1"
                >男</el-radio>
                <el-radio
                  v-model="formData.sex"
                  :label="2"
                >女</el-radio>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
            </div>

            <div class="clickUpload">
              <div class="clickUpText">
                <img
                  class="dataImg"
                  v-if="!!formData.facePictureUrl"
                  :src="formData.facePictureUrl"
                />
                <template v-else>
                  <img
                    class="bg-img"
                    src="@/assets/img/ownerManagement/img_zhaopian2@2x.png"
                    alt=""
                  />
                  <div>点击添加人脸照片</div>
                </template>
              </div>
              <el-upload
                :headers="token"
                ref="uploaduserlogo"
                class="mini-upload"
                limit="1"
                action="/czc-community/upload/uploadFile"
                :on-success="uploadsuccess"
                :before-upload="beforeAvatarUpload"
                :auto-upload="true"
                name="file"
              >
              </el-upload>
            </div>
          </div>
        </div>

        <div class="formContent-item">
          <div class="formContent-item_title">证件信息</div>

          <el-form-item label="证件类型">
            <el-select
              v-model="formData.idType"
              class="width100"
            >
              <el-option
                v-for="(item, index) in idTypeArray"
                :key="index"
                :label="item.label"
                :value="item.status"
              >{{
                                item.label
                            }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="证件号码"
            class="width100"
          >
            <el-input
              v-model="formData.idNumber"
              placeholder="请输入证件号码"
              maxlength="18"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="户籍地址"
            class="width100"
          >
            <el-input
              v-model="formData.permanentAddress"
              placeholder="请输入户籍地址"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="签发机关"
            class="width100"
          >
            <el-input
              v-model="formData.issuingAuthority"
              placeholder="请输入签发机关"
            ></el-input>
          </el-form-item>
          <el-form-item label="有效期">
            <el-date-picker
              class="width100"
              v-model="effectiveDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="选择开始日期"
              end-placeholder="选择结束日期"
              @change="effectiveDateToggle"
              :editable="false"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="国籍">
            <el-select
              v-model="formData.nationality"
              clearable
              class="width100"
            >
              <el-option
                v-for="(item, index) in nationalityArray"
                :key="index"
                :label="item.label"
                :value="item.status"
              >{{
                                item.label
                            }}</el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="籍贯">
            <el-select
              v-model="formData.nativePlace"
              clearable
              class="width100"
            >
              <el-option
                v-for="(item, index) in nativePlaceArray"
                :key="index"
                :label="item.name"
                :value="item.code"
              >{{
                                item.name
                            }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族">
            <el-select
              v-model="formData.nation"
              clearable
              class="width100"
            >
              <el-option
                v-for="(item, index) in nationArray"
                :key="index"
                :label="item.name"
                :value="item.code"
              >{{
                                item.name
                            }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker
              class="width100"
              v-model="formData.birthDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              :picker-options="pickerOptions"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </div>

        <div class="formContent-item">
          <div class="formContent-item_title"><span class="show-required-icon-star"></span> 绑定房产和车位</div>
          <div class="ownerScroll">
            <div
              class="formContent-formList house"
              v-for="(item, index) in formData.houseList"
              :key="index"
            >
              <div class="block-title">
                <div class="floor list-title">
                  {{
                                        `${item.buildingName} ${!!item.unitName ? CheckChinese(item.unitName, '单元') : ''}${
                                            item.roomNumber
                                        }`
                                    }}
                </div>
                <img
                  class="bg-img"
                  src="@/assets/img/ownerManagement/bg_card@2x.png"
                  alt=""
                />
                <img
                  class="bg-imgIoc"
                  src="@/assets/img/ownerManagement/icon_building@2x.png"
                  alt=""
                />
              </div>

              <div class="el-form">
                <el-form-item
                  label="类型"
                  required
                  label-width="70px"
                >
                  <el-select
                    v-model="item.householdType"
                    clearable
                    @change="householdTypeHide(item)"
                  >
                    <el-option
                      v-for="(item, index) in householdTypeArray"
                      :key="index"
                      :label="item.label"
                      :value="item.status"
                    >{{ item.label }}</el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="入住时间"
                  label-width="70px"
                >
                  <el-date-picker
                    v-model="item.checkInDate"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="date"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </div>

              <div
                class="block-title car"
                v-for="(items, indexs) in item.parkingList"
                :key="indexs"
              >
                <div class="floor list-title">
                  {{ `${items.garageName}${items.areaName || items.partitionName || ''}-${items.parkingNumber}` }}
                </div>
                <span
                  class="remove list-title"
                  @click="removeCard(indexs, item)"
                >移除</span>
                <img
                  class="bg-img"
                  src="@/assets/img/ownerManagement/bg_card@2x.png"
                  alt=""
                />
                <img
                  class="bg-imgIoc"
                  src="@/assets/img/ownerManagement/icon_car@2x.png"
                  alt=""
                />
              </div>
              <!-- <div
                class="addHouse block-title"
                v-if="!!formData.houseList.length"
                @click="addCard(item)"
              >
                <div class="floor list-title">绑定车位</div>
                <img
                  class="bg-img"
                  src="@/assets/img/ownerManagement/bg_card@2x.png"
                  alt=""
                />
                <img
                  class="bg-imgIoc"
                  src="@/assets/img/ownerManagement/icon_car@2x.png"
                  alt=""
                />
                <img
                  class="add"
                  src="@/assets/img/ownerManagement/btn_add@2x.png"
                />
              </div> -->
              <el-button
                class="removeHouseButton"
                type="primary"
                @click="removeHouse(index)"
                v-if="formData.houseList.length !== 0"
              >删除房产</el-button>
            </div>
            <div
              class="addHouse block-title"
              v-if="formData.houseList.length == 0"
              @click="addHouse()"
            >
              <div class="floor list-title">绑定房产</div>
              <img
                class="bg-img"
                src="@/assets/img/ownerManagement/bg_card@2x.png"
                alt=""
              />
              <img
                class="bg-imgIoc"
                src="@/assets/img/ownerManagement/icon_building@2x.png"
                alt=""
              />
              <img
                class="add"
                src="@/assets/img/ownerManagement/btn_add@2x.png"
              />
            </div>
            <el-button
              class="addHouseButton"
              type="primary"
              @click="addHouse()"
              v-if="formData.houseList.length !== 0"
            >新增房产</el-button>
          </div>
        </div>
      </div>
    </el-form>

    <div class="buttons">
      <el-button @click="closes">取消</el-button>
      <el-button
        type="primary"
        @click="addEdit()"
      >保存</el-button>
    </div>
  </div>
</template>
<script>
export default {
  name: 'ownerManagementAdd',
  props: {
    params: {
      type: Object
    },
    islook: {
      type: Boolean,
      default: false
    },
    isAdd: {
      type: Boolean,
      default: true
    }
  },
  filters: {
    matchingVal (val, arr) {
      let v = '';
      if (!!val) {
        arr.forEach((item) => {
          if (!!item.status && item.status === val) {
            v = item.label;
          } else if (!!item.code && item.code === val) {
            v = item.name;
          }
        });
      }
      return v;
    }
  },
  data () {
    return {
      token: {
        [localStorage.getItem('CZC_token') && 'Authorization']: 'Bearer ' + localStorage.getItem('CZC_token')
      },
      pickerOptions: {
        disabledDate (val) {
          // return val.getTime() < Date.now() - 8.64e7;
          return +new Date(val) > +new Date();
        }
      },
      effectiveDate: [],
      formData: {
        name: '',
        phone: '',
        personnelNumber: '',
        sex: '',
        remarks: '',
        facePictureUrl: '',
        id: 0,
        idType: 1,
        idNumber: '',
        permanentAddress: '',
        issuingAuthority: '',
        effectiveDateStart: '',
        effectiveDateEnd: '',
        nationality: 1,
        nativePlace: '',
        nation: '',
        birthDate: '',
        houseList: []
      },
      formCols: [
        [
          {
            label: '姓名',
            prop: 'name',
            slot: 'name',
            input: true
          },
          {
            label: '手机号',
            prop: 'phone',
            slot: 'phone',
            input: true
          },
          {
            label: '人员编号',
            prop: 'personnelNumber',
            slot: 'personnelNumber',
            input: true
          },
          {
            label: '性别',
            prop: 'sex',
            slot: 'sex'
          },
          {
            label: '备注',
            prop: 'remarks',
            slot: 'remarks'
          }
        ]
      ],
      formCols2: [
        [
          {
            label: '证件类型',
            prop: 'idType',
            slot: 'idType'
          },
          {
            label: '证件号码',
            prop: 'idNumber',
            slot: 'idNumber',
            input: true
          },
          {
            label: '户籍地址',
            prop: 'permanentAddress',
            slot: 'permanentAddress',
            input: true
          },
          {
            label: '签发机关',
            prop: 'issuingAuthority',
            slot: 'issuingAuthority',
            input: true
          },
          {
            label: '有效期',
            prop: 'effectiveDate',
            slot: 'effectiveDate'
          },
          {
            label: '国籍',
            prop: 'nationality',
            slot: 'nationality'
          },
          {
            label: '籍贯',
            prop: 'nativePlace',
            slot: 'nativePlace'
          },
          {
            label: '民族',
            prop: 'nation',
            slot: 'nation'
          },
          {
            label: '出生日期',
            prop: 'birthDate',
            slot: 'birthDate'
          }
        ]
      ],
      formCols3: [
        [
          {
            label: '类型',
            prop: 'householdType',
            slot: 'householdType',
            showRequired: true
          },
          {
            label: '入住时间',
            prop: 'checkInDate',
            slot: 'checkInDate'
          }
        ]
      ],
      nationalityArray: [
        {
          status: 1,
          label: '中国'
        },
        {
          status: 2,
          label: '其他'
        }
      ],
      idTypeArray: [
        {
          status: 1,
          label: '居民身份证'
        },
        {
          status: 2,
          label: '居民户口簿'
        },
        {
          status: 3,
          label: '暂住证'
        },
        {
          status: 4,
          label: '其他'
        }
      ],
      householdTypeArray: [
        {
          status: 1,
          label: '业主'
        },
        {
          status: 2,
          label: '亲属'
        },
        {
          status: 3,
          label: '租客'
        },
        {
          status: 4,
          label: '承租人'
        },
        {
          status: 5,
          label: '普通员工'
        }
      ],
      formRules: {
        name: [this.$valid.selectRequired('填写姓名')],
        phone: [this.$valid.patternPhone('填写手机号')],
        // idNumber: [this.$valid.inputRequired('证件号码')]
      },
      communityArr: [],
      garageArr: []
    };
  },
  created () {
    this.$store.dispatch('collapse', true);

    if (!!this.params.id) {
      this.getDetails(this.params.id);
    } else {
      if (this.$parent.thisLeftData.type == 'room') {
        this.formData.houseList = [
          {
            checkInDate: '',
            householdType: 1,
            buildingName: this.$parent.thisLeftData.buildingName,
            unitName: this.$parent.thisLeftData.unitName,
            roomNumber: this.$parent.thisLeftData.houseName,
            houseId: this.$parent.thisLeftData.houseId,
            parkingList: []
          }
        ];
      }
    }

    this.getTenantsTree();
  },
  beforeDestroy () {
    this.$store.dispatch('collapse', false);
  },
  computed: {
    nationArray () {

      return this.$store.getters['getNationArray'];
    },
    nativePlaceArray () {
      return this.$store.getters['getNativeArray'];
    }
  },
  methods: {
    getDetails (id) {
      let url = '/czc-community/scResident/find/' + id;
      this.$http
        .get(url)
        .then(({ data, status, msg }) => {
          if (0 === status) {
            let { effectiveDateStart, effectiveDateEnd } = data;
            if (effectiveDateStart == null || effectiveDateEnd == null) {
              effectiveDateStart = '';
              effectiveDateEnd = '';
            }
            this.effectiveDate = [effectiveDateStart, effectiveDateEnd];
            this.formData = data;
          } else {
            this.$message.error(msg);
          }
        })
        .catch(() => { });
    },
    lookFormCols (cols) {
      this[cols][0].forEach((item, index) => {
        if (!!item.input) {
          item.input = false;
        }
      });
    },
    uploadsuccess (response, file, fileList) {
      this.$refs.uploaduserlogo.clearFiles();
      if (0 === response.status) {

        this.formData.facePictureUrl = response.data;
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    effectiveDateToggle (va) {
      let arr = va;
      if (!arr) {
        arr = ['', ''];
      }
      this.formData.effectiveDateStart = arr[0];
      this.formData.effectiveDateEnd = arr[1];
    },
    addHouse () {
      new Promise((resolve) => {
        this.$store.dispatch('addPopup', {
          url: '/ownerManagement/stepPage/poptreeSelect.vue',
          width: '500px',
          height: '400px',
          props: {
            num: 1,
            list: this.formData.houseList || [],
            tenantsTree: this.communityArr,
            callback: resolve
          },
          title: '选择房产',
          notip: true
        });
      }).then((res) => {
        if (res.length > 0) {
          res.forEach((item, index) => {
            let newObj = {
              checkInDate: '',
              householdType: 1,
              buildingName: item.buildingName,
              unitName: item.unitName,
              roomNumber: item.roomNumber,
              houseId: item.houseId,
              parkingList: []
            };
            let isExit = this.formData['houseList'].some((is) => {
              return is.houseId == item.houseId;
            });
            if (!isExit) {
              this.formData['houseList'].push(newObj);
            }
          });
        }
      });
    },
    addCard (itemObj) {
      if (itemObj.householdType !== 1) {
        this.$message.error('只能业主才能绑定车位');
        return;
      }
      new Promise((resolve) => {
        this.$store.dispatch('addPopup', {
          url: '/ownerManagement/stepPage/poptreeSelect.vue',
          width: '500px',
          height: '400px',
          props: {
            num: 2,
            list: itemObj.parkingList || [],
            tenantsTree: this.garageArr,
            callback: resolve
          },
          title: '选择车位',
          notip: true
        });
      }).then((res) => {
        if (res.length > 0) {
          res.forEach((item, index) => {
            let newObj = {
              parkingId: item.parkingId,
              parkingNumber: item.parkingNumber,
              partitionName: item.partitionName,
              garageName: item.garageName
            };
            let isExit = itemObj['parkingList'].some((is) => {
              return is.parkingId == item.parkingId;
            });
            if (!isExit) {
              itemObj['parkingList'].push(newObj);
            }
          });
        }
      });
    },
    removeHouse (index) {
      this.formData['houseList'].splice(index, 1);
    },
    removeCard (index, itemObj) {
      itemObj['parkingList'].splice(index, 1);
    },
    closes () {
      this.$emit('clerOwnerStatus');
    },
    addEdit () {
      let _this = this;
      if (this.formData.houseList.length === 0) {
        this.$message.error('房产必须绑定');
        return;
      }

      this.$refs['ruleForm'].validate((valid) => {

        if (valid) {
          let url = '/czc-community/scResident/add';
          let params = this.formData;
          if (!_this.isAdd) {
            url = '/czc-community/scResident/update';
          }
          this.$http
            .post(url, params)
            .then(({ status, msg }) => {
              if (status == 0) {
                this.$message.success(msg);
                this.closes();
              } else {
                this.$message.error(msg);
              }
            })
            .catch(() => { });
        } else {
          return false;
        }
      });
    },
    getTenantsTree () {
      this.$http.get('/czc-community/assets/tree/community/find', { buildingType: 1 }).then(({ status, data, msg }) => {
        if (status === 0 && data) {
          this.dimension(data);
          this.communityArr = data;
        }
      });
      this.$http.get('/czc-community/assets/tree/garage/find').then(({ status, data, msg }) => {
        if (status === 0 && data) {
          this.garageArr = data;
        }
      });
    },
    dimension (arr) {
      arr.map((item, index) => {
        if (!!item.children) {
          this.dimension(item.children);
          if (item.type == 'unit') {
            item.name = this.CheckChinese(item.name, '单元');
          } else if (item.type == 'building') {
            item.name = this.CheckChinese(item.name, '楼栋');
          }
        }
      });
    },
    CheckChinese (val, name) {
      var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
      let newVal = val;
      if (!reg.test(val)) {
        newVal = val + name;
      }
      return newVal;
    },
    householdTypeHide (item) {
      if (item.householdType !== 1) {
        item.parkingList = [];
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import '../style.scss';
.formContent-item .ownerScroll {
    height: calc(100vh - 250px);
    overflow: auto;
    padding-right: 10px;
    &::-webkit-scrollbar {
        width: 5px;
    }
    &::-webkit-scrollbar-track {
        border-radius: 10px;
        background: #f4f7f9a8;
    }
    &::-webkit-scrollbar-thumb {
        border-radius: 10px;
        background: #c6c4c4a9;
    }
    .addHouse {
        cursor: pointer;
        margin-bottom: 20px !important;
        img.add {
            margin-left: 20px;
            width: 13px;
        }
    }

    .block-title.car {
        margin-bottom: 20px;
        &:nth-of-type(2n) {
            margin-right: 20px;
        }
    }

    .formContent-formList.house {
        flex-wrap: wrap;
        &::after {
            content: '';
            width: 100%;
            height: 1px;
            background: #e0e1e3;
            margin-bottom: 20px;
        }
        .el-form {
            width: calc(100% - 220px);
            /deep/ .el-date-editor.el-input {
                width: 100%;
            }
        }
    }
    .removeHouseButton {
        width: 80px;
        height: 32px;
        margin-bottom: 20px;
    }
}
</style>
