<template>
  <div class="establish" style="padding-top: 42px">
    <Demonstration />
    <div bordered class="list-box bg-white" v-for="(item, index) in list" :key="index">
      <div
        class="list-item"
        :style="{ 'border-bottom': listIndex === item.length - 1 ? '' : '1px solid #eee;' }"
        v-for="(listItem, listIndex) in item"
        :key="listIndex"
      >
        <div class="w-full flex flex-nowrap justify-between items-center">
          <view v-if="listItem.title">
            <div class="flex items-center" v-if="listItem.type !== -1">
              <view class="putong-title">{{ listItem.title }}</view>
              <span v-if="listItem.isTrue" style="color: red; font-size: 20px">*</span>
            </div>
            <div class="flex items-center" v-else>
              <view class="shu"></view>
              <view class="shu-title">{{ listItem.title }}</view>
            </div>
          </view>
          <div class="flex-1 flex justify-end">
            <!-- <u-switch v-if="listItem.type === 1" v-model="codeValue['CJBL-YLMS']" /> -->
            <u-upload
              v-if="listItem.type === 2"
              name="part"
              accept="image/*"
              :action="action"
              :show-upload-list="false"
              :custom-btn="true"
              @on-success="successUpload"
            >
              <img slot="addBtn" src="@/common/icon/idcard.png" class="img-icon" />
            </u-upload>
            <div v-else-if="listItem.type === 3" style="width: 174px">
              <u-input
                input-align="right"
                :value="codeValue[listItem.code]"
                placeholder="请输入"
                @blur="chanegIpt($event, listItem.code)"
                style="text-align: right"
              />
              <div class="text-red-400 font-12" style="text-align: right" v-if="!isFit && listItem.code === 'CJBL-idCard'">
                身份证号输入有误!
              </div>
            </div>
            <u-radio-group class="w-full" :value="codeValue[listItem.code]" v-else-if="listItem.type === 4" name="radioGroup">
              <div
                class="w-full flex justify-between items-center"
                style="height: 78rpx"
                @click="clickRadio(listItem.code, radioItem.name)"
                v-for="radioItem in listItem.listItem"
                :key="radioItem.id"
              >
                <view class="flex-1 putong-title">
                  {{ radioItem.name }}
                </view>
                <u-radio
                  @change="changeRadio($event, listItem.code)"
                  :disabled="isDisabled(listItem.code, radioItem.name)"
                  :key="radioItem.id"
                  :name="radioItem.id"
                >
                </u-radio>
              </div>
            </u-radio-group>
            <u-radio-group
              :disabled="sexIsDisabled('CJBL-idCard')"
              :value="codeValue[listItem.code]"
              v-else-if="listItem.type === 41"
              name="radioGroup"
            >
              <u-radio
                @change="changeRadio($event, listItem.code)"
                v-for="(radioItem, radioIndex) in listItem.listItem"
                :key="radioItem.id"
                :name="radioItem.id"
              >
                <view class="ml-2" :class="radioIndex === listItem.listItem.length - 1 ? '' : 'mr-2'">{{ radioItem.name }}</view>
              </u-radio>
            </u-radio-group>
          </div>
        </div>
      </div>
    </div>
    <u-toast ref="uToast" />
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations } from 'vuex';
import Demonstration from 'components/Demonstration/Demonstration';

export default {
  components: { Demonstration },
  data: () => ({
    action: '',
    codeValue: {
      'CJBL-YLMS': false,
      'CJBL-NAME': null,
      'CJBL-SEX': null,
      'CJBL-nation': null,
      'CJBL-idCard': null,
      'CJBL-YSBL': 'AS急性脑卒中',
    },
    list: [
      // [{ title: '演练模式', type: 1, isTrue: false }],
      [
        {
          title: '信息填写',
          type: -1,
          isTrue: false,
        },
        { title: '扫描身份证', type: 2, isTrue: false },
        { title: '姓名', type: 3, code: 'CJBL-NAME', isTrue: true },
        {
          title: '性别',
          type: 41,
          code: 'CJBL-SEX',
          isTrue: true,
          listItem: [
            { name: '女', id: 0 },
            { name: '男', id: 1 },
          ],
        },
        { title: '民族', type: 3, code: 'CJBL-nation', isTrue: false },
        { title: '身份证号', type: 3, code: 'CJBL-idCard', isTrue: false },
        {
          title: '疑似诊断',
          code: 'CJBL-YSBL',
          type: -1,
          isTrue: false,
        },
        {
          title: '',
          code: 'CJBL-YSBL',
          type: 4,
          isTrue: false,
          listItem: [
            { name: 'AS急性脑卒中', id: 'AS急性脑卒中' },
            { name: 'AMI急性心肌梗死', id: 'AMI急性心肌梗死' },
            { name: 'ATI急性创伤', id: 'ATI急性创伤' },
            { name: 'AGB急性消化道出血', id: 'AGB急性消化道出血' },
          ],
        },
      ],
    ],
    dropList: [],
    bodyStyle: { textAlign: 'center', height: '240px', padding: '24px 24px 0 24px', position: 'relative', overFlow: 'hidden' },
    visible: false,
    isActive: true,
    active: 0,
    role: '',
    isFit: true, // 身份证号是否符合验证规则
    isWatch: false,
  }),
  computed: {
    ...mapGetters('project', ['projectId']),
    ...mapState('carbasics', ['globalData', 'firstAidId', 'detailValueType']),
  },

  onLoad(options) {
    this.role = options.role;
    this.action = uni.$u.api.identifyWords;
    this.getData();
  },

  methods: {
    ...mapMutations('carbasics', ['setRefreshList']),
    // 获取病例信息
    async getData() {
      try {
        const param = { firstAidId: this.firstAidId };
        const data = await this.$u.api.getPatient(param);
        console.log('data: ', data);
        if (data && data.firstAidId) {
          this.codeValue = {
            'CJBL-NAME': data.name,
            'CJBL-SEX': data.gender,
            'CJBL-nation': data.nation,
            'CJBL-idCard': data.idcard,
            'CJBL-YSBL': data.suspected || 'AS急性脑卒中',
          };
          setTimeout(() => {
            this.isWatch = true;
          }, 100);
        }
      } catch (error) {
        console.log('error: ', error);
      }
    },
    // 上传图片成功时
    successUpload(res) {
      const { code, data } = res;
      let obj = { ...this.codeValue };
      if (code === 200) {
        obj['CJBL-NAME'] = data.name;
        obj['CJBL-SEX'] = data.sex;
        obj['CJBL-idCard'] = data.idCardNo;
        obj['CJBL-nation'] = data.nation;
        this.codeValue = { ...obj };
        const param = {
          firstAidId: this.firstAidId,
          gender: data.sex,
          idcard: data.idCardNo,
          name: data.name,
          nation: data.nation,
        };
        this.updateData(param);
      }
    },
    // 判断当前选项是否可点
    isDisabled(code, name) {
      if (code === 'CJBL-YSBL' && name !== 'AS急性脑卒中') {
        return true;
      } else {
        return false;
      }
    },
    sexIsDisabled(code) {
      if (this.codeValue[code] && this.codeValue[code].length > 0) {
        return true;
      }
    },
    // 点击了疑似病例的其他选项
    clickRadio(code, name) {
      if (code === 'CJBL-YSBL' && name !== 'AS急性脑卒中') {
        // this.$message.warning('请联系系统代理商开通该功能');
        this.$refs.uToast.show({
          title: '请联系系统代理商开通该功能',
          type: 'warning',
        });
      }
    },
    // 单选改变事件
    changeRadio(e, questionCode) {
      this.codeValue[questionCode] = e;
      let param = { firstAidId: this.firstAidId };
      if (questionCode === 'CJBL-SEX') {
        param.gender = e;
      } else if (questionCode === 'CJBL-YSBL') {
        param.suspected = e;
      }
      this.updateData(param);
    },
    // 输入框失去焦点
    iptBlur(e, code) {
      if (code === 'CJBL-idCard') {
        if (this.codeValue['CJBL-idCard']) {
          this.isFit = this.isIdentityId(this.codeValue['CJBL-idCard']);
          const idcard = this.codeValue['CJBL-idCard'];
          if (this.codeValue['CJBL-idCard'].length === 15) {
            this.codeValue['CJBL-SEX'] = (idcard[idcard.length - 1] - 0) % 2;
          } else if (this.codeValue['CJBL-idCard'].length === 18) {
            this.codeValue['CJBL-SEX'] = (idcard[idcard.length - 2] - 0) % 2;
          }
        } else {
          this.isFit = true;
        }
      }
      this.chanegIpt(e, code);
    },
    // 输入框改变事件
    chanegIpt(e, questionCode) {
      this.codeValue[questionCode] = e;
      const param = { firstAidId: this.firstAidId };
      if (questionCode === 'CJBL-NAME') {
        param.name = e;
      } else if (questionCode === 'CJBL-nation') {
        param.nation = e;
      } else if (questionCode === 'CJBL-idCard') {
        param.idcard = e;
      }
      if (questionCode !== 'CJBL-idCard' || (questionCode === 'CJBL-idCard' && e.length === 18)) {
        this.updateData(param, 1);
      }
    },
    // 验证身份证
    isIdentityId(identityId) {
      var patrn = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/; //长度或格式校验
      //地区校验
      var aCity = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外',
      };
      // 出生日期验证
      var sBirthday = (identityId.substr(6, 4) + '-' + Number(identityId.substr(10, 2)) + '-' + Number(identityId.substr(12, 2))).replace(
          /-/g,
          '/',
        ),
        d = new Date(sBirthday);
      // 身份证号码校验 最后4位  包括最后一位的数字/字母X
      var sum = 0,
        weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
        codes = '10X98765432',
        codes1 = '10x98765432';
      for (var i = 0; i < identityId.length - 1; i++) {
        sum += identityId[i] * weights[i];
      }
      var last = codes[sum % 11]; //计算出来的最后一位身份证号码
      var last1 = codes1[sum % 11]; //计算出来的最后一位身份证号码

      var errorMsg = true;
      if (identityId === '') {
        errorMsg = false;
      } else if (!patrn.exec(identityId)) {
        errorMsg = false;
      } else if (!aCity[parseInt(identityId.substr(0, 2))]) {
        errorMsg = false;
      } else if (sBirthday != d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate()) {
        errorMsg = false;
      } else if (identityId[identityId.length - 1] != last && identityId[identityId.length - 1] != last1) {
        errorMsg = false;
      }
      return errorMsg;
    },
    // 修改患者信息
    async updateData(param, type) {
      try {
        await this.$u.api.updatePatient(param);
        if (!type) {
          this.$refs.uToast.show({
            title: '修改成功',
            type: 'ssuccess',
          });
        }
      } catch (error) {
        this.$refs.uToast.show({
          title: '修改失败',
          type: 'warning',
        });
      }
    },
  },
  watch: {
    codeValue: {
      handler(val) {
        console.log('val: ', val);
        if (!this.isWatch) return;
        this.iptBlur(val['CJBL-idCard'], 'CJBL-idCard');
      },
      deep: true,
    },
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() {},
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {},
  // 页面周期函数--监听页面隐藏
  onHide() {},
  // 页面周期函数--监听页面卸载
  onUnload() {},
  // 页面处理函数--监听用户下拉动作
  onPullDownRefresh() {
    uni.stopPullDownRefresh();
  },
  // 页面处理函数--监听用户上拉触底
  onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  /* onPageScroll(event) {}, */
  // 页面处理函数--用户点击右上角分享
  /* onShareAppMessage(options) {}, */
};
</script>

<style scoped>
/deep/.u-radio__label {
  margin-left: 0 !important;
  margin-right: 0 !important;
}
.putong-title {
  margin-left: 24rpx;
  font-size: 32rpx;
  font-family: OPPOSans-Bold, OPPOSans;
  font-weight: bold;
  color: #3e3d4d;
}
.shu {
  width: 16rpx;
  height: 40rpx;
  background: linear-gradient(136deg, #7bc0ff 0%, #4d88ff 100%);
  border-radius: 40rpx;
  opacity: 1;
  margin-right: 8rpx;
}
.shu-title {
  font-size: 36rpx;
  font-family: Open Sans-Bold, Open Sans;
  font-weight: bold;
  color: #3e3d4d;
}
.img-icon {
  height: 24px;
  width: 24px;
  color: #717171;
}
.btn-box {
  padding: 16px;
}
.list-box {
  border-radius: 4px;
  overflow: hidden;
  box-sizing: border-box;
  margin: 0 0 0.75rem 0;
  padding: 0 32rpx;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5;
  list-style: none;
  font-feature-settings: 'tnum';
  position: relative;
}
.list-item {
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
}
</style>
