<template>
  <view class="">
    <custom-nav-bar position="fixed" color="black" left-text="党员注册" left-arrow />

    <view class="form-list">
      <view class="form-body">
        <view class="flex flex-v-center flex-between">
          <view class="label">
            <text>所属党委</text>
            <text class="red" v-if="!disabled">*</text>
          </view>
          <view class="label-value flex flex-v-center">
            <block v-if="!disabled">
              <picker @change="bindPickerChange" data-name="partyOrganName" range-key="branchName"
                :value="form.partyOrganName" :range="partyOrganizationList">
                <view style="color: #000000" v-if="form.partyOrganId !== ''">{{ form.partyOrganName }}</view>
                <view style="color: #999" v-if="form.partyOrganId === ''">请选择所属党委</view>
              </picker>
              <image class="ic-xia" src="/static/packages/people/images/ic-xia.png"></image>
            </block>
            <block v-else>
              {{form.partyOrganName}}
            </block>
          </view>
        </view>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>常住地社区</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <view class="label-value picker flex flex-v-center flex-between">
          <block v-if="!disabled">
            <view :class="form.communityId ? 'picker-line' : 'picker-text'" data-name="常住地社区" @tap="onOpenVisible">
              {{ form.communityName }}
            </view>
            <image class="ic-xia" src="/static/packages/people/images/ic-xia.png" @tap="onOpenVisible"></image>
          </block>
          <block v-else>
            {{ form.communityName }}
          </block>
        </view>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>常住小区</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <view class="label-value picker flex flex-v-center flex-between">
          <block v-if="!disabled">
            <view :class="form.villageId ? 'picker-line' : 'picker-text'" @tap="onOpenVisible">{{ form.villageName }}
            </view>
            <image class="ic-xia" src="/static/packages/people/images/ic-xia.png" @tap="onOpenVisible"></image>
          </block>
          <block v-else>
            {{form.villageName}}
          </block>
        </view>
      </view>

      <view class="flex">
        <view class="form-body form-col">
          <view class="label">
            <text>楼栋（街）</text>
            <text v-if="!disabled" class="red">*</text>
          </view>
          <block v-if="!disabled">
            <input class="flex1 textarea-class" @input="headleInput" :value="form.street" type="text" data-name="street"
              placeholder="请输入" />
          </block>
          <block v-else>
            {{form.street}}
          </block>
        </view>
        <view class="form-body form-col">
          <view class="label">
            <text>单元（巷）</text>
            <text v-if="!disabled" class="red">*</text>
          </view>
          <input v-if="!disabled" class="flex1 textarea-class" @input="headleInput" :value="form.lane" type="text"
            data-name="lane" placeholder="请输入" />
          <block v-else>
            {{form.lane}}
          </block>
        </view>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>房号</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <input v-if="!disabled" class="flex1 textarea-class pd-left" @input="headleInput" :value="form.houseCode"
          type="text" data-name="houseCode" placeholder="请输入" />
        <block v-else>
          {{form.houseCode}}
        </block>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>姓名</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <input v-if="!disabled" class="flex1 textarea-class" @input="headleInput" :value="form.name" type="text"
          data-name="name" placeholder="请输入" />
        <block v-else>
          {{form.name}}
        </block>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>性别</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <block v-if="!disabled">
          <van-radio-group v-model="form.sex" data-name="sex" shape="dot" direction="horizontal">
            <van-radio :name="1" icon-size="32rpx" checked-color="#FE3B53">男</van-radio>
            <van-radio :name="2" icon-size="32rpx" checked-color="#FE3B53">女</van-radio>
          </van-radio-group>
        </block>
        <block v-else>
          {{form.sex=== 1 ? '男' : '女'}}
        </block>
      </view>

      <view class="form-body">
        <view class="flex flex-v-center flex-between">
          <view class="label">
            <text>出生年月</text>
            <text v-if="!disabled" class="red">*</text>
          </view>
          <view class="label-value flex flex-v-center">
            <block v-if="!disabled">
              <picker mode="date" :value="form.birthDate" :start="startDate" data-name="birthDate" :end="endDate"
                @change="bindPickerChange">
                <view class="uni-input" v-if="form.birthDate !== ''">{{form.birthDate}}</view>
                <view class="uni-input" style="color: #999;" v-if="form.birthDate === ''">请选择出生年月</view>
              </picker>
              <image class="ic-xia" src="/static/packages/people/images/ic-xia.png"></image>
            </block>
            <block v-else>
              {{getDateTime(form.birthDate)}}
            </block>
          </view>
        </view>
      </view>

      <view class="form-body">
        <view class="flex flex-v-center flex-between">
          <view class="label">
            <text>学历</text>
            <text v-if="!disabled" class="red">*</text>
          </view>
          <view class="label-value flex flex-v-center">
            <block v-if="!disabled">
              <picker @change="bindPickerChange" range-key="label" data-name="education" :value="form.education"
                :range="educationList">
                <view style="color: #000000" v-if="form.education !== ''">{{ educationList[form.education].label }}
                </view>
                <view style="color: #999" v-if="form.education === ''">请选择</view>
              </picker>
              <image class="ic-xia" src="/static/packages/people/images/ic-xia.png"></image>
            </block>
            <block v-else>
              <view style="color: #000000" v-if="educationList.length !== 0">{{ educationList[form.education].label }}
              </view>
            </block>
          </view>
        </view>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>工作单位</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <input v-if="!disabled" class="flex1 textarea-class" @input="headleInput" :value="form.workAddress" type="text"
          data-name="workAddress" placeholder="请输入" />
        <block v-else>
          {{form.workAddress}}
        </block>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>职务</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <input v-if="!disabled" class="flex1 textarea-class" @input="headleInput" :value="form.duties" type="text"
          data-name="duties" placeholder="请输入" />
        <block v-else>{{form.duties}}</block>
      </view>

      <view class="form-body form-col">
        <view class="label">
          <text>联系方式</text>
          <text v-if="!disabled" class="red">*</text>
        </view>
        <input v-if="!disabled" class="flex1 textarea-class" @input="headleInput" :value="form.mobile" type="text"
          data-name="mobile" placeholder="请输入" />
        <block v-else>{{form.mobile}}</block>
      </view>

      <view class="form-button">
        <block v-if="!disabled">
          <block v-if="options.userid === undefined">
            <van-button v-if="checked" @click="handSubmit" data-name="新增" block color="#FE3B53">提交</van-button>
            <van-button v-else block color="#D9E2EE">提交</van-button>
          </block>
          <block v-else>
            <van-button @click="handSubmit" data-name="修改" block color="#FE3B53">提交</van-button>
          </block>
        </block>
        <block v-else>
          <van-button @click="headerEite" block color="#FE3B53">编辑</van-button>
        </block>
      </view>

    </view>
    <van-popup v-model:show="isVisible" round position="bottom">
      <van-cascader v-model="currentValue" :title="cascaderTitle" :options="optionData" :field-names="defaultFieldNames"
        @finish="onCloseVisible" @close="onCloseVisible" @change="onChangeVisible" />
    </van-popup>
  </view>
</template>

<script>
  import * as peopleApi from '@/api/peopleApi';
  import * as publicApi from '@/api/publicApi';
  import utils from '@/utils/util'
  import util from '@/utils/util.map'
  export default {
    data() {
      const currentDate = this.getDate({
        format: true
      })
      return {
        options: {},
        disabled: false,
        form: {
          partyOrganId: '',
          partyOrganName: '',
          street: '',
          lane: '',
          houseCode: '',
          name: '',
          sex: '1',
          birthDate: '',
          education: '',
          workAddress: '',
          duties: '',
          mobile: '',
          communityId: '',
          communityName: '请选择',
          villageId: '',
          villageName: '请选择',
        },
        minDate: new Date(2020, 0, 1),
        maxDate: new Date(2025, 5, 1),
        columns: [],
        educationList: [],
        fileList: [],
        checked: '1',
        partyOrganizationList: [],


        // 级连选择器数据 start
        cascaderTitle: '',
        isVisible: false,
        FiledVisible: true,

        optionData: [],
        currentTile: '请选择',

        // 选择后的名称
        currentValue: null,

        // 选择后的id
        // 级联选择默认显示字段
        // 级连选择器数据 end
        defaultFieldNames: {
          text: 'name',
          value: 'id',
          children: 'children'
        },
      }
    },
    computed: {
      startDate() {
        return this.getDate('start');
      },
      endDate() {
        return this.getDate('end');
      }
    },
    async onLoad(options) {
      this.options = options
      this.getTypeApi('people_party_member_education', 'educationList');
      this.deptTreeApi();
      this.partyOrganizationAll();
      if (options.userid !== undefined) {
        this.disabled = true
        this.partyOrganizationInfo();
      }
    },
    methods: {
      getDateTime(time) {
        return util.getDateTime(time, 2)
      },
      headerEite() {
        this.disabled = false
      },
      async partyOrganizationInfo() {
        const res = await peopleApi.partyMemberInfoApi({});
        if (res.data) {
          this.form = res.data
        }
      },
      async deptTreeApi() {
        // 获取所在村/社区
        const res = await publicApi.deptTreeApi();
        if (res.data && res.data.length) {
          this.optionData = res.data
        }
      },
      async partyOrganizationAll() {
        const res = await peopleApi.partyOrganizationAllApi();
        if (res.data) {
          this.partyOrganizationList = res.data
        }
      },
      //  获取群众点单字典
      async getTypeApi(dictType, list) {
        const vm = this;
        const res = await publicApi.getDictDataApi({
          dictType: dictType,
          pageNo: 1,
          pageSize: 100
        });
        if (res.code === 0) {
          vm[list] = res.data.list
        }
      },
      bindPickerChange(e) {
        let name = e.target.dataset.name
        if (name === 'partyOrganName') {
          this.form.partyOrganId = this.partyOrganizationList[e.detail.value].id
          this.form.partyOrganName = this.partyOrganizationList[e.detail.value].branchName
        } else {
          this.form[name] = e.detail.value
        }
      },
      headleInput(event) {
        const {
          value
        } = event.detail;
        let name = event.target.dataset.name
        this.form[name] = value;
      },
      handSubmit(event) {
        // 校验必填字段
        console.log(this.form)
        const formKey = Object.keys(utils.filterParams(this.form));
        console.log("formKey", formKey)
        const required = [
          'partyOrganId',
          'communityId',
          'villageId',
          'street',
          'lane',
          'houseCode',
          'name',
          'sex',
          'birthDate',
          'education',
          'workAddress',
          'duties',
          'mobile',
        ];
        console.log(this.form)
        const isRequired = required.every((e) => formKey.includes(e));
        console.log(isRequired)
        if (!isRequired) {
          return wx.showToast({
            title: '星号为必填！',
            icon: 'none',
          });
        }

        const {
          name
        } = event.target.dataset;
        console.log(name)
        if (name === '修改') {
          console.log('修改');
          this.addSubmitUpdate();
        } else {
          this.addSubmit();
        }
      },
      async addSubmitUpdate() {
        const res = await peopleApi.partyMemberUpdate(this.form);
        if (res.data) {
          wx.showToast({
            title: '修改成功',
            icon: 'none',
          });

          let time = setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            });
            clearTimeout(time);
          }, 1500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      async addSubmit() {
        const res = await peopleApi.partyMemberCreate(this.form);
        if (res.data) {
          wx.showToast({
            title: '注册成功',
            icon: 'none',
          });

          let time = setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            });
            clearTimeout(time);
          }, 1500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      getDate(type) {
        const date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        if (type === 'start') {
          year = year - 60;
        } else if (type === 'end') {
          year = year + 2;
        }
        month = month > 9 ? month : '0' + month;
        day = day > 9 ? day : '0' + day;
        return `${year}-${month}-${day}`;
      },
      onCheckbox(event) {
        this.checked = event
      },

      onOpenVisible(e) {
        this.isVisible = true
        this.cascaderTitle = e.currentTarget.dataset.name
      },

      onCloseVisible() {
        this.isVisible = false
      },

      onChangeVisible(e) {
        if (this.cascaderTitle === '常住地社区') {
          this.form.communityName = e.selectedOptions[e.tabIndex].name
          this.form.communityId = e.value
        } else {
          this.form.villageName = e.selectedOptions[e.tabIndex].name
          this.form.villageId = e.value
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .form-list {
    width: 100%;
  }

  .form-body {
    font-size: 32rpx;
    font-weight: 400;
    color: #333333;
    padding: 40rpx 40rpx 38rpx;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 50%;
      bottom: 0;
      transform: translateX(-50%);
      width: 678rpx;
      height: 1px;
      background-color: #EFEFEF;
    }

    .label {
      font-size: 28rpx;
      font-weight: 400;
      color: #333333;
    }

    .label-value {
      font-size: 32rpx;
      font-weight: 500;
      color: #000000;
      line-height: 32rpx;

      .ic-xia {
        margin-left: 27rpx;
        width: 32rpx;
        height: 32rpx;
      }
    }

    .picker {
      margin-top: 24rpx;
    }

    .picker-text {
      font-size: 32rpx;
      font-weight: 400;
      color: #999999;
    }

    .picker-line {
      flex: 1;
    }

    .textarea-class {
      margin-top: 26rpx;
      width: 100%;
      font-size: 32rpx;
      font-weight: 400;
    }

    .form-msg {
      font-size: 26rpx;
      font-weight: 400;
      color: #999999;
      line-height: 26rpx;
      margin-top: 28rpx;
    }

    .location {
      width: 32rpx;
      height: 32rpx;
    }

    .location-info {
      margin-top: 26rpx;

      input {
        font-size: 32rpx;
        font-weight: 400;
      }
    }
  }

  .form-col {
    display: flex;
    align-items: center;
    justify-content: space-between;
    text-align: right;

    .textarea-class {
      margin-top: 0;
    }

    .card-placeholder {
      font-size: 32rpx;
      font-weight: 400;
      color: #000000;
    }
  }

  .form-location {
    padding: 20rpx 35rpx;
    border-radius: 16rpx;
  }

  .form-treaty {
    padding: 83rpx 40rpx 32rpx;

    .ic-check {
      width: 32rpx;
      height: 32rpx;
    }

    .checbox-text {
      font-size: 28rpx;
      font-weight: 400;
      color: #000000;
      line-height: 28rpx;

      .jump-to {
        color: var(--item-dominant-color);
      }
    }
  }

  .form-button {
    margin-top: 34rpx;
    padding: 25rpx 36rpx;
  }

  .form-button-body {
    height: 80rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #ffffff;
    line-height: 80rpx;
    text-align: center;
    background: #c1c1c1;
    border-radius: 8rpx;
  }

  .form-button-body-select {
    background: var(--item-dominant-color);
  }

  .form-image {
    margin: 20rpx 0rpx 20rpx 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .form-image>view {
    width: 31.3%;
    position: relative;
    margin-right: 13.5rpx;
  }

  .form-image>view>image:nth-child(1) {
    width: 100%;
    height: 200rpx;
    border-radius: 10rpx;
  }

  .form-image>view>image:nth-child(2) {
    position: absolute;
    top: -0rpx;
    right: 0rpx;
    width: 40rpx;
    height: 40rpx;
  }

  .camera {
    width: 160rpx;
    height: 160rpx;
  }

  .pd-left {
    text-align: left;
    padding-left: 35px;
  }

  .img-icon {
    height: 20px;
  }
</style>