<template>
  <section class="scoreFamily">
    <ai-list v-show="!detailShow">
      <template slot="title">
        <ai-title title="家庭积分" :isShowBottomBorder="true" :instance="instance" :isShowArea="true" @change="getList()" v-model="areaId"></ai-title>
      </template>
      <template slot="content">
        <ai-search-bar bottomBorder>
          <template slot="left">
            <el-select size="small" v-model="searchObj.isPositive" placeholder="积分是否大于0" clearable @change="page.current = 1,getList()">
              <el-option
                v-for="(item,i) in isPositiveList"
                :key="i"
                :label="item.dictName"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </template>
          <template slot="right">
            <el-input
              v-model="searchObj.con"
              size="small"
              placeholder="户主姓名"
              @keyup.enter.native="page.current = 1, getList()"
              @clear="search.current = 1, search.con = '', getList()"
              clearable
              suffix-icon="iconfont iconSearch" />
          </template>
        </ai-search-bar>
        <ai-search-bar class="mt10">
          <template slot="left">
            <ai-download :instance="instance" type="primary" url="/app/appvillagerintegraldetail/listExport" :params="params" fileName="家庭积分"></ai-download>
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="tableData"
          :col-configs="colConfigs"
          :total="page.total"
          ref="aitableex"
          :current.sync="page.current"
          :size.sync="page.size"
          @getList="getList">
          <el-table-column label="操作" slot="options" fixed="right" align="center" width="180">
            <template v-slot="{row}">
              <div class="table-options">
                <!-- <el-button type="text" title="编辑" @click="edit(row)" :disabled="!$permissions('app_appvillagerintegralfamily_edit')">编辑</el-button> -->
                <el-button type="text" title="家庭成员" @click="familyMember(row)" :disabled="!$permissions('app_appvillagerintegralfamilymember_edit')">家庭成员</el-button>
                <el-button type="text" :disabled="!$permissions('app_appvillagerintegralfamily_detail')" title="详情" @click="goDetail(row)">详情</el-button>
              </div>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <detail v-if="detailShow" @goBack="goBack" :detailInfo='detailInfo' :instance='instance' :dict='dict'></detail>
    <ai-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :customFooter="true"
        :destroyOnClose="true"
        @close="init('ruleForm')"
        width="520px">
      <div class="form_div">
        <el-form ref="ruleForm" :model="dialogInfo" :rules="formRules" size="small" label-suffix="："
                 label-width="120px">
          <el-form-item label="类型" prop="personType">
            <el-radio-group v-model="dialogInfo.personType" @change="typeChange"
                            :disabled="dialog.title.indexOf('修改')!=-1">
              <el-radio label="0">户籍居民</el-radio>
              <el-radio label="1">外来人员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="dialog.title.indexOf('家庭')!=-1?'户主':'姓名'" prop="name">
            <el-row type="flex" :gutter="8">
              <el-col>
                <el-input v-model="dialogInfo.name" disabled clearable/>
              </el-col>
              <el-col>
                <ai-person-select :instance="instance" :key="personUrl" :url="personUrl" @selectPerson="getSelect"
                                  v-if="dialog.title.indexOf('添加')!=-1"></ai-person-select>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="dialogInfo.idNumber" disabled clearable/>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input type="number" v-model="dialogInfo.phone" maxlength="11" clearable/>
          </el-form-item>
          <el-form-item label="所属组" prop="villageGroup" v-if="dialog.title.indexOf('家庭')!=-1">
            <el-select v-model="dialogInfo.villageGroup" placeholder="请选择...">
              <el-option
                  v-for="(item,i) in dict.getDict('integralVillageGroup')"
                  :key="i"
                  :label="item.dictName"
                  :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status" v-if="dialog.title.indexOf('家庭')!=-1">
            <el-select v-model="dialogInfo.status" placeholder="请选择...">
              <el-option
                  v-for="(item,i) in dict.getDict('integralRuleStatus')"
                  :key="i"
                  :label="item.dictName"
                  :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="与户主关系" prop="householdRelation" v-if="dialog.title.indexOf('成员')!=-1">
            <el-select
                v-model="dialogInfo.householdRelation"
                placeholder="请选择"
                size="mini"
                clearable
                style="width:216px;"
            >
              <el-option
                  v-for="(item,i) in dict.getDict('householdRelation')"
                  :label="item.dictName"
                  :key="i"
                  :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer" slot="footer">
        <el-button @click="dialog.visible=false" size="medium">取消</el-button>
        <el-button @click="onConfirm('ruleForm')" type="primary" size="medium">确认</el-button>
      </div>
    </ai-dialog>
    <ai-dialog class="family-list"
        title="成员列表"
        :visible.sync="addMemberVisible"
        :customFooter="true"
        :destroyOnClose="true"
        width="780px">
      <!-- <p class="add_btn">
        <span class="iconfont iconAdd" @click="addFamily()"></span>
        <span @click="addFamily()">添加家庭成员</span>
      </p> -->
      <ai-table
          :tableData="familyList"
          :col-configs="familycolConfigs"
          :total="familyPage.total"
          :current.sync="familyPage.current"
          :size.sync="familyPage.size"
          @getList="familyMember(rowInfo)">
        <el-table-column label="与户主关系" slot="householdRelation" align="center" width="120">
          <template v-slot="{row}">
            <span v-if="row.householdName == 1">户主</span>
            <span v-else>{{dict.getLabel('householdRelation', row.householdRelation)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" slot="personType" align="center" width="120">
          <template v-slot="{row}">户籍居民</template>
        </el-table-column>
        <el-table-column label="身份证号" slot="idNumber" align="center" width="165">
          <template v-slot="{row}">
            <ai-id mode="show" :show-eyes="false" :value="row.idNumber"/>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" slot="options" align="center">
          <template v-slot="{row}">
            <el-button type="text"
                       v-if="row.householdRelation!=11&&$permissions('app_appvillagerintegralfamilymember_edit')"
                       icon="iconfont iconEdit" title="编辑" @click="editFamily(row)"/>
            <el-button type="text"
                       v-if="row.householdRelation!=11&&$permissions('app_appvillagerintegralfamilymember_del')"
                       icon="iconfont iconDelete" title="删除" @click="deleteFamily(row.id)"/>
          </template>
        </el-table-column> -->
      </ai-table>
      <div class="dialog-footer" slot="footer">
        <el-button @click="addMemberVisible=false" size="medium">关 闭</el-button>
      </div>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from 'vuex';
import detail from './detail'

export default {
  name: 'scoreFamily',
  label: "家庭积分",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  components: {detail},
  data() {
    return {
      areaId: '',
      searchObj: {
        personType: '',
        villageGroup: '',
        status: '',
        con: '',
        isPositive: '',
      },
      isPositiveList: [{
        dictName: '是',
        dictValue: '1'
      }, {
        dictName: '否',
        dictValue: '0'
      }],
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      familyPage: {
        current: 1,
        size: 10,
        total: 0
      },
      exportParams: {},
      tableData: [],
      dialog: {
        title: '添加家庭',
        visible: false
      },
      dialogInfo: {
        personType: '0',
        name: '',
        idNumber: '',
        phone: '',
        villageGroup: '',
        status: '',
        areaId: '',
        householdRelation: '',
        avatar: ''
      },
      addMemberVisible: false,
      detailShow: false,
      personUrl: '',
      familyList: [],
      familyId: '',
      detailInfo: {},
      rowInfo: {}

    }
  },
  computed: {
    ...mapState(['user']),
    params () {
      return {
        ...this.searchObj,
        areaId: this.areaId,
        exportType: 0
      }
    },
    colConfigs() {
      return [
        {
          prop: 'name',
          label: '户主',
        },
        {
          prop: 'phone',
          align: 'center',
          label: '联系电话',
        },
        {
          prop: 'householdAreaName',
          align: 'center',
          label: '所在村',
        },
        {
          prop: 'familyIntegral',
          align: 'center',
          label: '家庭积分',
        },
        {
          prop: 'familyUsedIntegral',
          align: 'center',
          label: '已用积分',
        },
        {
          prop: 'familySurplusIntegral',
          align: 'center',
          label: '剩余积分',
        },
        {
          prop: 'familyNum',
          align: 'center',
          label: '成员数',
        },
      ]
    },
    familycolConfigs() {
      return [
        // {
        //   prop: 'householdRelation',
        //   align: 'center',
        //   label: '与户主关系',
        //   render(h, {row}) {
        //     return h('span', {}, _.$dict.getLabel('householdRelation', row.householdRelation))
        //   }
        // },
        {
          slot: 'householdRelation',
        },
        {
          prop: 'residentType',
          align: 'center',
          label: '类型',
          formart: v => this.dict.getLabel('residentType', v)
        },
        {
          prop: 'name',
          align: 'center',
          label: '姓名',
        },
        {
          prop: 'idNumber',
          align: 'center',
          slot: 'idNumber',
          label: '身份证号',
          width: 165,
        },
        {
          prop: 'phone',
          align: 'center',
          label: '联系电话',
          width: 120,
        }

      ]
    },
    formRules() {
      let IdNumberPass = (rule, value, callback) => {
        if (value) {
          console.log(this.idCardNoUtil);
          if (this.idCardNoUtil.checkIdCardNo(value)) {
            callback();
          } else {
            callback(new Error("身份证号格式错误"));
          }
        } else {
          callback(new Error("请输入身份证号"));
        }
      };
      if (this.dialog.title.indexOf('家庭') != -1) {

        return {
          personType: [{required: true, message: "请选择类型", trigger: 'change'}],
          name: [{required: true, message: "请填写户主", trigger: 'change'}],
          idNumber: [{required: true, validator: IdNumberPass, trigger: 'change'}],
          phone: [{required: true, message: "请填写联系电话", trigger: 'blur'}],
          villageGroup: [{required: true, message: "请选择所属组", trigger: 'change'}],
          status: [{required: true, message: "请选择状态", trigger: 'change'}],
          householdRelation: [{required: true, message: "请选择与户主关系", trigger: 'change'}]
        }
      } else {
        return {
          personType: [{required: true, message: "请选择类型", trigger: 'change'}],
          name: [{required: true, message: "请填写户主", trigger: 'change'}],
          idNumber: [{required: true, validator: IdNumberPass, trigger: 'change'}],
          villageGroup: [{required: true, message: "请选择所属组", trigger: 'change'}],
          status: [{required: true, message: "请选择状态", trigger: 'change'}],
          householdRelation: [{required: true, message: "请选择与户主关系", trigger: 'change'}]
        }
      }
    }
  },
  created() {
    this.areaId = this.user.info.areaId;
    this.dict.load('integralVillageGroup', 'integralRuleStatus', 'integralPersonType', 'householdRelation', 'residentType');
    this.getList();
  },
  methods: {
    getList() {
      this.instance.post("/app/appresident/familyIntegral", null, {
        params: {
          ...this.searchObj,
          ...this.page,
          areaId: this.areaId
        }
      }).then(res => {
        if (res.code == 0) {
          this.tableData = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    typeChange(val) {
      val == '0' ? this.personUrl = '/app/appresident/list?fileStatus=0' : this.personUrl = '/app/apprecurrentpopulation/list?fileStatus=0';
      this.dialogInfo.name = "";
      this.dialogInfo.idNumber = "";
      this.dialogInfo.phone = "";
      this.dialogInfo.avatar = "";
      this.dialogInfo.areaId = "";
    },
    add() {
      this.dialog.visible = true;
      this.dialog.title = '添加家庭';
    },
    addFamily() {
      this.dialog.visible = true;
      this.dialog.title = '添加成员';
    },
    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialog.title.indexOf('家庭') != -1) {
            this.instance.post("/app/appvillagerintegralfamily/addOrUpdate", {
              ...this.dialogInfo,
            }, null).then(res => {
              if (res.code == 0) {
                this.dialog.visible = false;
                if (this.dialog.title.indexOf('添加') != -1) {
                  this.$message.success("添加成功")
                } else {
                  this.$message.success("修改成功")
                }
                this.getList();
              }
            })
          } else {
            this.instance.post("/app/appvillagerintegralfamilymember/addOrUpdate", {
              ...this.dialogInfo,
              familyId: this.familyId,
              familyIdNumber: this.rowInfo.idNumber,
              familyName: this.rowInfo.name
            }, null).then(res => {
              if (res.code == 0) {
                this.dialog.visible = false;
                if (this.dialog.title.indexOf('添加') != -1) {
                  this.$message.success("添加成功")
                } else {
                  this.$message.success("修改成功")
                }
                this.familyMember(this.rowInfo);
                this.getList();
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    init(formName) {
      this.$refs[formName].clearValidate();
      Object.keys(this.dialogInfo).forEach(e => {
        this.dialogInfo[e] = ''
      })
      this.dialogInfo.personType = '0';
      this.personUrl = '';
    },
    reset() {
      Object.keys(this.searchObj).forEach(e => {
        this.searchObj[e] = ''
      });
      this.getList();
    },
    edit(row) {
      this.dialog.visible = true;
      this.dialog.title = '修改家庭';
      this.dialogInfo = {...row}
    },
    editFamily(row) {
      this.dialog.visible = true;
      this.dialog.title = '修改成员';
      this.dialogInfo = {...row}
    },
    deleteFamily(ids) {
      ids && this.$confirm("是否要删除该家庭成员", {
        type: 'error'
      }).then(() => {
        this.instance.post("/app/appvillagerintegralfamilymember/delete", null, {
          params: {ids}
        }).then(res => {
          if (res?.code == 0) {
            this.$message.success("删除成功!")
            this.familyMember(this.rowInfo);
          }
        })
      }).catch(() => {
      })
    },
    getSelect(val) {
      console.log(val)
      if (val) {

        this.dialogInfo.name = val.name;
        this.dialogInfo.idNumber = val.idNumber;
        this.dialogInfo.avatar = val.photo;
        if (this.dialogInfo.personType == 0) {
          this.dialogInfo.areaId = val.householdAreaId;
        } else {
          this.dialogInfo.areaId = val.currentAreaId;
        }
      } else {
        this.dialogInfo.name = '';
        this.dialogInfo.idNumber = '';
        this.dialogInfo.phone = '';
        this.dialogInfo.areaId = '';
        this.dialogInfo.avatar = '';
        this.$refs['rules'].clearValidate();
      }

    },
    familyMember(row) {
      this.rowInfo = {...row}
      this.familyId = row.id;
      this.instance.post(`/app/appresident/detail?id=${row.id}`).then(res => {
        if (res.code == 0) {
          this.familyList = res.data.family;
          this.familyPage.total = res.data.family.length;
          this.addMemberVisible = true;
        }
      })

    },
    goBack() {
      this.detailShow = false;
    },
    goDetail(row) {
      this.detailInfo = {...row};
      this.detailShow = true;
    }
  }
}
</script>

<style lang="scss" scoped>
.scoreFamily {
  height: 100%;
  background: #f3f6f9;
  overflow: auto;

  .form_div {
    width: 380px;
  }

  .add_btn {
    color: #5088FF;
    font-size: 14px;
    line-height: 36px;
    text-align: right;

    span {
      cursor: pointer;
    }

    span:nth-child(2) {
      margin-left: 4px;
    }

  }

  .iconfont {
    cursor: pointer;
  }

  .iconAll_Profile {
    padding: 0 8px;
  }
  .family-list{
    ::v-deep .el-table--small{
      font-size: 14px!important;
    }
  }
}
</style>
