<template>
  <div v-loading="loading">
    <el-form :rules="rules2" ref="OthersForm1" :model="formData2" class="login_form">
      <el-form-item prop="isHasOther" label="是否有其他赡养人" ref="isHasOther">
        <el-select
          v-model="formData2.isHasOther"
          placeholder="请选择"
          @change="selectDependant"
          ref="select"
        >
          <el-option
            v-for="item in dependants"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form
      :rules="rules"
      ref="OthersForm"
      v-if="isDependant"
      :model="formData"
      class="login_form"
    >
      <el-form-item prop="name" label="其他赡养人姓名" ref="name">
        <el-input
          v-model="formData.name"
          autocomplete="off"
          ref="verificationName"
          placeholder="请填写姓名"
          style="width: 220px"
          @blur="selectOtherInfo1"
        ></el-input>
      </el-form-item>

      <el-form-item prop="sex" label="其他赡养人性别" ref="sex">
        <el-radio-group v-model="formData.sex" class="sex-radio" @change="selectOtherInfoVisit">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="phone" label="其他赡养人电话" ref="phone">
        <el-input
          v-model="formData.phone"
          autocomplete="off"
          placeholder="请填写常用联系电话或手机号"
          style="width: 220px"
          @blur="selectOtherInfo2"
        ></el-input>
      </el-form-item>
      <el-form-item prop="relation" label="与被赡养人关系" ref="relation">
        <el-select
          v-model="formData.relation"
          placeholder="请选择"
          @change="selectDependantRelationship"
        >
          <el-option
            v-for="item in dependantRelationships"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="isDependantRelationship"
        label="与被赡养人其他关系"
        prop="relationExt"
        ref="relationExt"
      >
        <el-input
          v-model="formData.relationExt"
          autocomplete="off"
          placeholder="请输入与被赡养人其他关系"
          style="width: 220px"
          @blur="relationExtOtherInfo"
        ></el-input>
      </el-form-item>

      <el-form-item prop="isHasGoOut" label="是否外出" ref="isHasGoOut">
        <el-select v-model="formData.isHasGoOut" placeholder="请选择" @change="selectGoOut()">
          <el-option
                  v-for="item in goOut"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="partner" v-if="formData.isHasGoOut == '是'">
        <el-form-item prop="outgoingCause" label="外出原因" ref="outgoingCause">
          <el-input
                  v-model="formData.outgoingCause"
                  autocomplete="off"
                  placeholder="请填写外出原因"
                  style="width: 220px"
                  @blur="selectOtherInfo3"
          ></el-input>
        </el-form-item>
      <div id="trigger4" v-show="false" style="width: 0;height: 0"></div>
      <el-form-item prop="outgoingplace" label="外出地点" ref="outgoingplace">
        <el-col
          class="ffff"
          :span="24"
          @click.native="clickPlace"
          :style="`color:${formData.outgoingplace === ''||formData.outgoingplace ==='请选择' ? '#409EFF':''}`"
        >{{formData.outgoingplace || '点击选择外出地点'}}</el-col>
      </el-form-item>
      <div id="trigger5" v-show="false" style="width: 0;height: 0"></div>
      <el-form-item prop="outgoingTime" label="最后一次离家时间" ref="outgoingTime">
        <el-col
          class="ss"
          :span="24"
          @click.native="clickDate"
          :style="`color:${formData.outgoingTime === ''||formData.outgoingTime ==='请选择' ? '#409EFF':''}`"
        >
          <!--{{formLabelAlign.address === '' ? '请选择' :formLabelAlign.address }}-->
          {{ formData.outgoingTime || '点击选择最后一次离家时间'}}
        </el-col>
        <!-- <el-button @click="clickDate" style="width: 220px;">{{formData.outgoingTime===''?"选择日期":formData.outgoingTime}}</el-button>-->
        <!-- 代码。。。。。。。。。。。。。。。。。。。。。。。。。。。 -->
        <!-- <mt-datetime-picker
                        class="opt_picker"
                        v-model.trim="date"
                        type="date"
                        ref="picker"
                        @confirm="changeDateValue()"
                        year-format="{value} 年"
                        month-format="{value} 月"
                >
        </mt-datetime-picker>-->
        <!-- <van-popup
          class="outgoingTime"
          v-model="popShow"
          position="bottom"
          :style="{ height: '40%'}"
        >
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="popShow = false"
            @confirm="onConfirm"
            @change="timeSelect"
          />
        </van-popup>-->
      </el-form-item>
      </div>
      <el-form-item prop="isHasPartner" label="是否有配偶" ref="isHasPartner">
        <el-select v-model="formData.isHasPartner" placeholder="请选择" class="sex-radio" @change="selectHasPartner">
          <el-option
                  v-for="item in goOut"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="partner" v-if="formData.isHasPartner == '是'">
        <el-form-item prop="name2" label="配偶姓名" ref="name2">
          <el-input
                  v-model="formData.name2"
                  autocomplete="off"
                  ref="verificationName"
                  placeholder="请填写姓名"
                  style="width: 220px"
                  @blur="selectOtherInfo4"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone2" label="配偶电话" ref="phone2">
          <el-input
                  v-model="formData.phone2"
                  autocomplete="off"
                  ref="verificationName"
                  placeholder="请填写联系电话"
                  style="width: 220px"
                  @blur="selectOtherInfo5"
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item prop="visit" label="平均一年探望次数" ref="visit">
        <el-select
          v-model="formData.visit"
          placeholder="请填写平均一年探望次数"
          @change="selectOtherInfoVisit"
        >
          <el-option
            v-for="item in dependantTimes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-image
      :src="require('../../assets/ic_tip.png')"
      style="position: fixed;top:10vh;right: 10px;width: 20px;"
      @click="toScroll"
    />
  </div>
</template>

<script>
import areaList from "../../util/area";
import date from "../../util/date";
import areaListList from "../../util/area1";
import { ownerUpdate } from "../../api";
import PickerExtend from "picker-extend";

export default {
  name: "other",
  props: ["id", "othersData", "clickTabIndex"],
  data() {
    let checkName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("赡养人姓名不能为空"));
      } else {
        let reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/;
        if (!reg.test(value)) {
          callback(new Error("请输入中文格式"));
        } else {
          callback();
        }
      }
    };
    let checkName1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("配偶姓名不能为空"));
      } else {
        let reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/;
        if (!reg.test(value)) {
          callback(new Error("请输入中文格式"));
        } else {
          callback();
        }
      }
    };
    return {
      oldId: "",
      index: "",
      mobileSelect4: "",
      mobileSelect5: "",
      othersList: {},
      show: false,
      loading: false,
      isShow: false,
      isDependant: false,
      isDependantRelationship: false,
      formData2: {
        isHasOther: ""
      },
      formData: {
        sex: "",
        phone: "",
        relation: "", //关系
        relationExt: "", //其他
        isHasGoOut:"是",// 是否外出
        outgoingplace: "",// 外出原因
        outgoingTime: "",
        outgoingCause:"",
        isHasPartner: '',  //是否有配偶
        name2: '',
        phone2: '',
        visit: "",
        name: ""
      },
      areaList: areaList,
      areaListList: areaListList,
      //   date: new Date(),
      date: date.date,
      dependants: [
        { value: "0", label: "是" },
        { value: "1", label: "否" }
      ],
      goOut: [
        { value: "是", label: "是" },
        { value: "否", label: "否" }
      ],
      dependantTimes: [
        { value: "0次", label: "0次" },
        { value: "1次", label: "1次" },
        { value: "2次及以上", label: "2次及以上" }
      ],
      dependantRelationships: [
        { value: "近亲属", label: "近亲属" },
        { value: "孙子女", label: "孙子女" },
        { value: "兄弟姐妹", label: "兄弟姐妹" },
        { value: "其他", label: "其他" }
      ],
      rules2: {
        isHasOther: [
          {
            required: true,
            message: "是否有其他赡养人不为空",
            trigger: ["blur", "change"]
          }
        ]
      },
      rules: {
        //数据校验规则
        name: [{ required: true, validator: checkName, trigger: "blur" }],
        phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
        isHasOther: [
          {
            required: true,
            message: "请选择是否有其他赡养人",
            trigger: "change"
          }
        ],
        relationExt: [
          {
            required: true,
            message: "与被其他赡养人关系不能为空",
            trigger: "blur"
          }
        ],
        visit: [
          {
            required: true,
            message: "请选择一年平均探望次数",
            trigger: "change"
          }
        ],
        isHasGoOut: [
          { required: true, message: "请选择是否外出", trigger: "blur" }
        ],
        outgoingplace: [
          { required: true, message: "请选择外出地点", trigger: "blur" }
        ],
        relation: [
          {
            required: true,
            message: "请选择与其他赡养人的关系",
            trigger: "change"
          }
        ],
        outgoingTime: [
          {
            required: true,
            message: "请选择最后一次离家时间",
            trigger: "change"
          }
        ],
        outgoingCause: [
          { required: true, message: "请填写外出原因", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择其他赡养人性别", trigger: "change" }
        ],
        isHasPartner: [
          {required: true, message: "请选择是否有配偶", trigger: "change"}
        ],
        name2: [{required: true, validator: checkName1, trigger: "blur"}],
        phone2: [
          {required: true, message: "请输入配偶联系电话", trigger: "change"}
        ]
      }
    };
  },
  methods: {
    timeSelect(picker, values) {
      picker.setColumnValues(1, this.date[values[0]]);
    },
    onConfirm(value) {
      console.log(value, "ssdsd");
      //this.formData.outgoingTime = year + "-" + month;
      //   this.Scroll();
      //   this.updateOlds();
      let c = value[0].slice(0, 4) + "-" + value[1].slice(0, 2);
      console.log(c);
      this.popShow = false;
    },
    relationExtOtherInfo() {
      this.$refs["OthersForm"].validateField("relationExt", emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds();
        } else {
          this.isColor = false;
          this.$emit("otherisColor", this.isColor, this.index);
          return false;
        }
      });
    },
    selectGoOut() {
        this.formData.outgoingCause = "";
        this.formData.outgoingplace = "";
        this.formData.outgoingTime="";
      this.selectOtherInfoVisit();
    },
    selectHasPartner(){
        this.formData.name2 = '';
        this.formData.phone2 = '';
      this.selectOtherInfoVisit();
    },
    selectOtherInfoVisit() {
      this.Scroll();
      this.updateOlds();
    },
    toScroll() {
      setTimeout(() => {
        this.$refs["OthersForm1"].validate((valid, obj) => {
          if (!valid) {
            let vKey = "";
            Object.keys(obj).forEach(item => {
              if (!vKey) {
                vKey = item;
              }
            });
            this.$refs[vKey].$el.scrollIntoView({
              behavior: "auto",
              block: "center",
              inline: "nearest"
            });
          }
        });
        this.$refs["OthersForm"].validate((valid, obj) => {
          if (!valid) {
            let vKey = "";
            Object.keys(obj).forEach(item => {
              if (!vKey) {
                vKey = item;
              }
            });
            this.$refs[vKey].$el.scrollIntoView({
              behavior: "auto",
              block: "center",
              inline: "nearest"
            });
          }
        });
      }, 200);
    },
    Scroll() {
      setTimeout(() => {
        this.$refs["OthersForm1"].validate(valid => {
          if (valid) {
            this.isColor = true;
            this.$emit("otherisColor", this.isColor, this.index);
          } else {
            this.isColor = false;
            this.$emit("otherisColor", this.isColor, this.index);
          }
        });
        this.$refs["OthersForm1"].clearValidate();
        if (this.formData2.isHasOther == "0") {
          this.$refs["OthersForm"].validate(valid => {
            if (valid) {
              this.isColor = true;
              this.$emit("otherisColor", this.isColor, this.index);
            } else {
              this.isColor = false;
              this.$emit("otherisColor", this.isColor, this.index);
            }
          });
          this.$refs["OthersForm"].clearValidate();
        }
      }, 200);
    },
    selectDependant(value) {
      this.isDependant = value == "0";
      this.Scroll();
      if (value == "0") {
        this.updateOlds();
      } else {
        this.updateOlds2();
        this.formData.name = "";
        this.formData.sex = "";
        this.formData.phone = "";
        this.formData.relation = "";
        this.formData.relationExt = "";
        this.formData.outgoingplace = "";
        this.formData.visit = "";
        this.formData.outgoingTime = "";
        this.formData.isHasGoOut="是";
        this.formData.isHasPartner= '';  //是否有配偶
        this.formData.name2= '';
        this.formData.phone2= '';
      }
    },
    selectDependantRelationship(value) {
      if (value === "其他") {
        this.isDependantRelationship = true;
      } else {
        this.isDependantRelationship = false;
        this.formData.relationExt = "";
      }
      this.Scroll();
      this.updateOlds();
    },
    clickPlace() {
      this.mobileSelect4.show();
    },
    // clickDate() {
    //     this.$refs.picker.open();
    // },
    clickDate() {
      this.mobileSelect5.show();
    },
    isDateString(str) {
      return /\d{4}(-|\/|.)\d{1,2}\1\d{1,2}/.test(str);
    },
    getYear(value) {
      return this.isDateString(value)
        ? value.split(" ")[0].split(/-|\/|\./)[0]
        : value.getFullYear();
    },
    getMonth(value) {
      return this.isDateString(value)
        ? value.split(" ")[0].split(/-|\/|\./)[1]
        : value.getMonth() + 1;
    },
    getDate(value) {
      return this.isDateString(value)
        ? value.split(" ")[0].split(/-|\/|\./)[2]
        : value.getDate();
    },
    changeDateValue() {
      let year = this.getYear(this.date);
      let month = this.getMonth(this.date);
      //let date = this.getDate(this.date);
      this.formData.outgoingTime = year + "-" + month;
      this.Scroll();
      this.updateOlds();
    },
    selectOtherInfo1() {
      this.$refs["OthersForm"].validateField("name", emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds({ id: this.oldId, name: this.formData.name });
        } else {
          //this.Scroll();
          this.updateOlds({ id: this.oldId, name: this.formData.name });
          this.isColor = false;
          this.$emit("otherisColor", this.isColor, this.index);
          return false;
        }
      });
    },
    selectOtherInfo2() {
      this.$refs["OthersForm"].validateField("phone", emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds({ id: this.oldId, phone: this.formData.phone });
        } else {
          //this.Scroll();
          this.updateOlds({ id: this.oldId, phone: this.formData.phone });
          this.isColor = false;
          this.$emit("otherisColor", this.isColor, this.index);
          return false;
        }
      });
    },
    // outgoingCause
    selectOtherInfo3() {
      this.$refs["OthersForm"].validateField("outgoingCause", emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds({ id: this.oldId, outgoingCause: this.formData.outgoingCause });
        } else {
          //this.Scroll();
          this.updateOlds({ id: this.oldId, outgoingCause: this.formData.outgoingCause });
          this.isColor = false;
          this.$emit("otherisColor", this.isColor, this.index);
          return false;
        }
      });
    },
    //name2
    selectOtherInfo4() {
      this.$refs["OthersForm"].validateField("name2", emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds({ id: this.oldId, name2: this.formData.name2 });
        } else {
          //this.Scroll();
          this.updateOlds({ id: this.oldId, name2: this.formData.name2 });
          this.isColor = false;
          this.$emit("otherisColor", this.isColor, this.index);
          return false;
        }
      });
    },
    //phone2
    selectOtherInfo5() {
      this.$refs["OthersForm"].validateField("phone2", emailError => {
        if (!emailError) {
          this.Scroll();
          this.updateOlds({ id: this.oldId, phone2: this.formData.phone2 });
        } else {
          //this.Scroll();
          this.updateOlds({ id: this.oldId, phone2: this.formData.phone2 });
          this.isColor = false;
          this.$emit("otherisColor", this.isColor, this.index);
          return false;
        }
      });
    },
    async updateOlds2() {
      this.loading = true;
      const result = await ownerUpdate({ id: this.oldId, otherInfo: "" });
      if (result.code === 0) {
        this.loading = false;
      }
    },
    async updateOlds() {
      const result = await ownerUpdate({
        id: this.oldId,
        otherInfo: JSON.stringify(this.formData)
      });
      if (result.code === 0) {
        console.log(result);
      }
    },
    removeExcess(data) {
      if (data) {
        data = JSON.parse(data);
      }
      return data;
    },
    getList() {
      if (this.othersData) {
        this.othersList = this.othersData;
        this.oldId = this.othersList._id;
        this.formData.outgoingplace = "";
        this.formData.outgoingTime = "";
        if (this.othersList.hasOwnProperty("otherInfo")) {
          if (this.othersList.otherInfo) {
            this.formData2.isHasOther = "0";
            this.isDependant = true;
            let data="";
            const result = this.removeExcess(this.othersList.otherInfo);
            if (!result.isHasGoOut) {
              if (result.outgoingplace || result.outgoingCause || result.outgoingTime) {
                data= "是";
              } else {
                data= "否";
              }
            }else
            {
              data=result.isHasGoOut
            }
            // console.log(this.formData.isHasGoOut,'this.formData.isHasGoOut');
            // console.log(this.formData,'this.formData');
            this.formData = {
              sex: result.sex,
              name: result.name,
              phone: result.phone,
              relationExt: result.relationExt, //其他
              isHasGoOut:data,
              outgoingplace: result.outgoingplace,
              outgoingTime: result.outgoingTime,
              isHasPartner:result.isHasPartner,
              outgoingCause:result.outgoingCause,
              name2:result.name2,
              phone2:result.phone2,
              visit: result.visit
            };
            if (result.relation === "其他") {
              this.isDependantRelationship = true;
              this.formData.relation = "其他";
            } else {
              this.isDependantRelationship = false;
              this.formData.relation = result.relation;
            }
          } else {
            this.formData2.isHasOther = "1";
            this.isDependant = false;
            this.isDependantRelationship = false;
          }
        }
        this.Scroll();
      }
    },
    cascading() {
      this.areaListList.dept.forEach((pro, pi) => {
        pro.id = pi + "";
        pro.childs.forEach((city, ci) => {
          city.id = pi + "" + ci;
          city.childs = city.area.map((area, ai) => {
            let obj = {};
            obj.id = pi + "" + ci + ai;
            obj.name = area;
            return obj;
          });
        });
      });
      let that = this;
      this.mobileSelect4 = new PickerExtend({
        trigger: "#trigger4",
        title: "选择地区",
        wheels: [{ data: this.areaListList.dept }],
        keyMap: {
          id: "id",
          value: "name",
          childs: "childs"
        },
        position: [0, 0], //初始化定位
        callback: function(indexArr, data) {
          let arr = [];
          data.forEach(item => {
            arr.push(item.name);
          });
          that.formData.outgoingplace = arr.join("/");
          that.Scroll();
          that.updateOlds({
            id: that.oldId,
            outgoingplace: that.formData.outgoingplace
          });
        }
      });
    },
    cascading1() {
      let that = this;
      this.mobileSelect5 = new PickerExtend({
        trigger: "#trigger5",
        title: "选择最后一次离家时间",
        wheels: [{ data: this.date }],
        position: [0, 0], //初始化定位
        callback: function(indexArr, data) {
          if (data.length === 1) {
            that.formData.outgoingTime = data[0].value;
          } else {
            that.formData.outgoingTime =
              data[0].value.slice(0, 4) + "-" + data[1].value.slice(0, 2);
          }
          that.Scroll();
          that.updateOlds({
            id: that.oldId,
            outgoingTime: that.formData.outgoingTime
          });
        }
      });
    }
  },
  watch: {
    id(newValue) {
      this.oldId = newValue;
    },
    clickTabIndex(newValue) {
      this.index = newValue;
    },
    othersData(newValue) {
      this.othersList = newValue;
    }
  },
  mounted() {
    this.oldId = this.id;
    this.index = this.clickTabIndex;
    this.getList();
    this.cascading();
    this.cascading1();
  }
};
</script>

<style scoped>
.sex-radio {
  width: 220px;
}
.opt_picker >>> .picker-slot-center:nth-child(3) {
  display: none;
}
.ss {
  text-align: left;
}
.ffff {
  text-align: left;
}
.partner {
  padding: 10px;
  border: 1px solid #eee;
  background-color: #f1f1f1;
}
</style>
