<template>
  <section style="height: 100%">
    <ai-detail class="add">
      <template #title>
        <ai-title :title="title" :isShowBack="true" :isShowBottomBorder="true" @onBackClick="cancel(false)"></ai-title>
      </template>
      <template #content>
        <el-form
          ref="rules"
          :model="forms"
          :rules="formRules"
          size="small"
          label-suffix="："
          label-width="136px">
          <ai-card title="基础信息" >
            <template #right  v-if="title=='网格员详情'">
              <span style="color:#2266FF;cursor: pointer;font-size: 12px;" class="iconfont iconEdit" v-if="editOne==false" @click="editOne=true">修改</span>
              <span style="color:#2266FF;margin-left: 16px;cursor: pointer;font-size: 12px;" v-if="editOne==true" @click="searchDetail(),editOne=false">取消</span>
              <span style="color:#2266FF;margin-left: 16px;cursor: pointer;font-size: 12px;" v-if="editOne==true" @click="save()">保存</span>
            </template>
            <template slot="content">
              <div class="above" v-if="editOne==true">
                <div class="left">
                  <el-form-item label="网格员姓名" prop="name" >
                    <el-input v-model="forms.name" placeholder="请选择网格员" disabled>
                      <template #append>
                        <ai-wechat-selecter :isMultiple="false" refs="addTags" :instance="instance" v-model="users" @change="getSelectPerson">
                          <el-button size="small" type="primary"><span style="color: #fff">选择成员</span></el-button>
                        </ai-wechat-selecter>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="选用日期" prop="selectionDate" >
                    <el-date-picker
                      v-model="forms.selectionDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      size="medium"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="身份证号" prop="idNumber" >
                      <el-input v-model="forms.idNumber" placeholder="请输入…" maxlength="18" show-word-limit></el-input>
                  </el-form-item>
                </div>
                <div class="right">
                  <el-form-item label="照片" prop="photo">
                    <!-- <ai-uploader :instance="instance" v-model="photoList" :limit="1" @change="photoChange"></ai-uploader> -->
                    <ai-avatar :instance="instance"  v-model="forms.photo"/>
                  </el-form-item>
                </div>
              </div>
              <div class="above" v-if="editOne==true">
                <div class="left">
                  <el-form-item label="出生日期" prop="birthday" >
                    <el-date-picker
                        v-model="forms.birthday"
                        type="date"
                        value-format="yyyy-MM-dd"
                        size="medium"
                        placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="联系电话" prop="phone" >
                    <el-input v-model.number="forms.phone" placeholder="请输入…" maxlength="11" show-word-limit></el-input>
                  </el-form-item>
                </div>
                <div class="right">
                  <el-form-item label="性别" prop="sex" >
                    <el-select size="medium" v-model="forms.sex" placeholder="请选择..." clearable>
                      <el-option
                        v-for="(item,i) in dict.getDict('sex')"
                        :key="i"
                        :label="item.dictName"
                        :value="item.dictValue"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="电子邮箱" prop="mail" >
                      <el-input v-model="forms.mail" placeholder="请输入…"></el-input>
                  </el-form-item>
                </div>
              </div>
              <template  v-if="editOne==false">
                <div class="above">
                  <div class="left">
                    <ai-wrapper label-width="120px"  :columnsNumber="1"  style="margin-top: 16px;">
                      <ai-info-item label="网格员姓名："><span >{{forms.name}}</span></ai-info-item>
                      <ai-info-item label="选用日期："><span >{{forms.selectionDate}}</span></ai-info-item>
                      <ai-info-item label="身份证号："><span >{{forms.idNumber}}</span></ai-info-item>
                      <ai-info-item label="性别："><span >{{dict.getLabel('sex', forms.sex)}}</span></ai-info-item>
                      <ai-info-item label="出生日期："><span >{{forms.birthday}}</span></ai-info-item>
                      <ai-info-item label="电子邮箱："><span >{{forms.mail}}</span></ai-info-item>
                    </ai-wrapper>
                  </div>
                  <div class="right">
                    <ai-wrapper label-width="120px"  :columnsNumber="1"  style="margin-top: 16px;">
                      <ai-info-item label="照片：" v-if="forms.photo">
                        <span >
                          <ai-uploader :instance="instance" v-model="photoList" disabled :limit="1" @change="photoChange"></ai-uploader>
                        </span>
                      </ai-info-item>
                      <ai-info-item label="联系电话："><span >{{forms.phone}}</span></ai-info-item>
                    </ai-wrapper>
                  </div>
                </div>
              </template>
            </template>
          </ai-card>
          <ai-card title="关联信息" >
            <template #right  v-if="title=='网格员详情'">
              <span style="color:#2266FF;cursor: pointer;font-size: 12px;" class="iconfont iconEdit" v-if="editTwo==false" @click="editTwo=true">修改</span>
              <span style="color:#2266FF;margin-left: 16px;cursor: pointer;font-size: 12px;" v-if="editTwo==true" @click="searchDetail(),editTwo=false">取消</span>
              <span style="color:#2266FF;margin-left: 16px;cursor: pointer;font-size: 12px;" v-if="editTwo==true" @click="save()">保存</span>
            </template>
            <template slot="content">
              <template v-if="editTwo==true">
                <el-form-item label="责任网格" prop="girdInfoList" style="margin-top: 8px;">
                  <!-- <el-tag
                    :key="index"
                    v-for="(tag,index) in forms.girdInfoList"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                    {{tag.girdName}}
                  </el-tag> -->
                  <el-form-item style="width: 100%" label-width="80px" :label="'网格' + (index + 1)" v-for="(item, index) in forms.girdInfoList" :key="'选项' + (index + 1)">
                    <div class="form-flex">
                      <el-select v-model="item.checkType" placeholder="请选择网格角色">
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                      <el-input disabled v-model="item.girdName" :maxlength="200" size="small" placeholder="请选择责任网格">
                        <template slot="append">
                          <el-button size="small" @click="currIndex = index, showGrid = true">选择网格</el-button>
                        </template>
                      </el-input>
                      <el-button type="danger" size="small" @click="removeGrid(index)">删除</el-button>
                    </div>
                  </el-form-item>
                  <el-button type="primary" size="small" @click="addGrid">添加选项</el-button>
                  <!-- <el-button size="small" @click="showGrid=true">选择网格</el-button> -->
                </el-form-item>
                <div class="above">
                  <div class="left">
                    <el-form-item label="是否特殊网格员" prop="isGirdMember" >
                      <el-radio-group v-model="forms.isGirdMember">
                        <el-radio label="0">否</el-radio>
                        <el-radio label="1">是</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="政治面貌" prop="politicsStatus" >
                      <el-select v-model="forms.politicsStatus" size="medium" placeholder="请选择..." clearable>
                        <el-option v-for="(item,i) in dict.getDict('politicsStatus')" :key="i" :label="item.dictName" :value="item.dictValue"></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="right">
                    <el-form-item label="特殊网格员" prop="girdMemberType" v-if="forms.isGirdMember==1">
                      <el-select v-model="forms.girdMemberType" size="medium" placeholder="请选择..." clearable>
                        <el-option v-for="(item,i) in dict.getDict('girdMemberType')" :key="i" :label="item.dictName" :value="item.dictValue"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="学历" prop="education" >
                      <el-select v-model="forms.education" size="medium" placeholder="请选择..." clearable>
                        <el-option v-for="(item,i) in dict.getDict('education')" :key="i" :label="item.dictName" :value="item.dictValue"></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
                <el-form-item label="个人简介" prop="introduction" >
                  <el-input
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="forms.introduction">
                  </el-input>
                </el-form-item>
                <el-form-item label="人生格言" prop="motto" >
                  <el-input
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="forms.motto">
                  </el-input>
                </el-form-item>
              </template>
              <template v-if="editTwo==false">
                <ai-wrapper label-width="120px" :columnsNumber="2" style="margin-top: 16px;">
                  <ai-info-item label="责任网格：" style="width: 100%;"><span v-html="girdInfoStr || '-'"></span></ai-info-item>
                  <ai-info-item label="是否特殊网格员："><span >{{forms.isGirdMember==1?'是':'否'}}</span></ai-info-item>
                  <ai-info-item label="特殊网格员：" v-if="forms.isGirdMember==1"><span >{{dict.getLabel('girdMemberType', forms.girdMemberType)}}</span></ai-info-item>
                  <ai-info-item label="政治面貌："><span >{{dict.getLabel('politicsStatus', forms.politicsStatus)}}</span></ai-info-item>
                  <ai-info-item label="学历："><span >{{dict.getLabel('education', forms.education)}}</span></ai-info-item>
                  <ai-info-item label="人生格言：" style="width: 100%;"><span >{{forms.motto}}</span></ai-info-item>
                  <ai-info-item label="个人简介：" style="width: 100%;"><span >{{forms.introduction}}</span></ai-info-item>
                </ai-wrapper>
              </template>
            </template>
          </ai-card>
        </el-form>
        <ai-dialog title="选择网格" :visible.sync="showGrid" :customFooter="true"  :destroyOnClose="true"  @opened="beforeSelectTree"  border  width="720px">
          <div class="grid">
            <el-tree :data="treeObj.treeList" :props="treeObj.defaultProps" node-key="id"  ref="tree" :check-strictly="true"  show-checkbox
              :default-checked-keys="currCheckedKeys" default-expand-all  highlight-current>
            </el-tree>
          </div>
          <div class="dialog-footer" slot="footer" >
            <el-button  size="medium" @click="showGrid=false">取消</el-button>
            <el-button  type="primary" size="medium" @click="getCheckedTree()">确认</el-button>
          </div>
        </ai-dialog>
      </template>
      <template #footer v-if="title=='添加网格员'">
        <el-button @click="cancel(false)" class="delete-btn footer-btn" >取 消</el-button>
        <el-button type="primary" @click="save()"  class="footer-btn">提 交</el-button>
      </template>
    </ai-detail>
  </section>
</template>

<script>
export default {
  name: "add",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    params: Object,
  },
  data() {
    return {
      users: [],
      currIndex: 0,
      forms: {
        birthday: "",
        education: "",
        girdId: "",
        girdInfoList: [],
        girdMemberType: "",
        id: "",
        introduction: "",
        isGirdMember: "",
        mail: "",
        motto: "",
        name: "",
        phone: "",
        photo: "",
        politicsStatus: "",
        selectionDate: "",
        sex: "",
        userId: "",
      },
      options: [{
        value: '2',
        label: '网格长'
      }, {
        value: '1',
        label: '网格员'
      }],
      showGrid: false,
      treeObj: {
        treeList: [],
        defaultProps: {
          children: "girdList",
          label: "girdName",
        },
        checkedKeys: [],
      },
      girdInfoStr: '',
      photoList: [],
      title: "添加网格员",
      editOne: false,
      editTwo: false,
    };
  },
  created() {
    if (this.params.id) {
      this.searchDetail();
      this.title = "网格员详情";
      this.editOne = false;
      this.editTwo = false;
    } else {
      this.title = "添加网格员";
      this.editOne = true;
      this.editTwo = true;
    }
  },
  computed: {
    currCheckedKeys () {
      if (this.forms && this.forms.girdInfoList[this.currIndex] && this.forms.girdInfoList[this.currIndex].id) {
        return [this.forms.girdInfoList[this.currIndex].id]
      }

      return []
    },
    formRules() {
      let phonePass = (rule, value, callback) => {
        let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
        if (value) {
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("联系电话格式错误"));
          }
        } else {
          callback(new Error("请输入联系电话"));
        }
      };
      return {
        name: [
          { required: true, message: "请填写网格员姓名", trigger: "change" },
        ],
        selectionDate: [
          { required: true, message: "请选择选用日期", trigger: "change" },
        ],
        phone: [{ required: true, validator: phonePass, trigger: "blur" }],
        girdInfoList: [
          { required: true, message: "请选择责任网络", trigger: "change" },
        ],
        mail: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        isGirdMember: [
          {
            required: true,
            message: "请选择是否特殊网格员",
            trigger: "change",
          },
        ],
      };
    },
  },
  methods: {
    cancel (isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh,
      })
    },

    removeGrid (index) {
      this.forms.girdInfoList.splice(index, 1)
    },

    addGrid () {
      this.forms.girdInfoList.push({
        id: '',
        girdName: '',
        checkType: ''
      })
    },
    photoChange(val) {
      this.forms.photo = val[0].url;
    },
    getSelectPerson(val) {
      this.forms.name = val[0].name;
      this.forms.phone = val[0].phone;
      this.forms.userId = val[0].sysUserId
    },
    getCheckedTree() {
      if (!this.$refs.tree.getCheckedNodes().length) {
        return this.$message.error('请选择网格')
      }

      if (this.$refs.tree.getCheckedNodes().length > 1) {
        return this.$message.error('不支持多选')
      }
      this.$set(this.forms.girdInfoList, this.currIndex, {
        ...this.$refs.tree.getCheckedNodes()[0],
        checkType: this.forms.girdInfoList[this.currIndex].checkType
      })
      this.showGrid = false;
    },
    handleClose(tag) {
      this.forms.girdInfoList.splice(this.forms.girdInfoList.indexOf(tag), 1);
    },
    beforeSelectTree() {
      this.treeObj.checkedKeys = [];
      this.instance.post(`/app/appgirdinfo/listAll`, null, null).then((res) => {
        if (res.code == 0) {
          this.treeObj.treeList = res.data;
          this.forms.girdInfoList.map((e) => {
            this.treeObj.checkedKeys.push(e.id);
          });
        }
      });
    },
    save() {
      this.$refs["rules"].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.forms.girdInfoList.length; i++) {
            if (!this.forms.girdInfoList[i].checkType) {
              return this.$message.error('请选择网格员类型')
            }
            if (!this.forms.girdInfoList[i].id) {
              return this.$message.error('请选择网格')
            }
          }

          this.instance
            .post(
              `/app/appgirdmemberinfo/addOrUpdate`,
              {
                ...this.forms,
                girdInfoListStr: this.forms.girdInfoList.map(v => v.girdName).join(',')
              },
              null
            )
            .then((res) => {
              if (res.code == 0) {
                if (this.title == "添加网格员") {
                  this.cancel(true)
                } else {
                  this.editOne = false;
                  this.editTwo = false;
                  this.searchDetail();
                }
              }
            });
        } else {
          return false;
        }
      });
    },
    searchDetail() {
      this.instance
        .post(`/app/appgirdmemberinfo/queryDetailById`, null, {
          params: { id: this.params.id },
        })
        .then((res) => {
          if (res.code == 0) {
            this.forms = { ...res.data };
            this.user = [{
              name: res.data.name,
              phone: res.data.phone,
              userId: res.data.id
            }]
            this.photoList = [{ url: this.forms.photo }];
            
            res.data.girdInfoList.forEach((e, index) => {
              this.girdInfoStr = this.girdInfoStr + `${e.checkType === '1' ? '网格员' : '网格长'}-${e.girdName}&emsp;`
            })
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.add {
  height: 100%;
    .form-flex {
      display: flex;
      align-items: center;

      & > .el-button {
        margin-left: 20px;
      }

      .el-input {
        width: 300px;
        margin-left: 20px;
      }

      ::v-deep .el-form-item__content {
        margin-left: 0!important;
      }
    }
  .ai-detail__title {
    background-color: #fff;
  }
  .ai-detail__content {
    .ai-detail__content--wrapper {
      .el-form {
        // background-color: #fff;
        // padding: 0 60px;
        .flex {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .el-form-item {
            width: 48%;
          }
          .buildingTypes {
            width: 100%;
          }
        }
      }
    }
  }
  ::v-deep .el-tag {
    margin-right: 8px;
    color: #333333;
  }
  .footer-btn {
    width: 92px;
  }
  .above{
    display: flex;
    .left, .right{
      flex: 1;
    }
  }
}
</style>
