from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
# -- coding: utf-8 --
import web
import re
urls = ('/', 'Index')
class Index:
    def GET(self):
        return '''
            
             <!DOCTYPE html>
                <html>
                    <head>
                        <meta charset="UTF-8">
                        <title>身份证号码校验系统</title>
                    </head>
                    <body>
                     <h1>身份证号码校验系统</h1>
                        <form action="validate_idcard.py" method="post">
                        <label for="idcard">请输入身份证号码：</label>
                        <input type="text" id="idcard" name="idcard" required>
                        
                        <input type="submit" value="校验">
                        </form>
                    </body>
                </html>
      '''


    def POST(self):
        data = web.input()
        idcard = data.get('idcard')
        if self.path == 'validate_idcard.py':
            result = self.validate_idcard(idcard)
            return result

    def calculate_check_digit(self, idcard):
        # 校验位字符集
        check_digits = '10X98765432'
            # 系数
        coefficients = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        # 将输入的15位身份证号升级到18位
        idcard = idcard[:6] + '19' + idcard[6:]

        # 计算校验位
        sum = 0
        for i in range(17):
            sum += int(idcard[i]) * coefficients[i]
        check_digit_index = sum % 11
        check_digit = check_digits[check_digit_index]

        return check_digit

    def validate_idcard(self, idcard):
        # 校验15位身份证号
        if len(idcard) == 15:
            # 升级到18位
            idcard = idcard[:6] + '19' + idcard[6:]
            check_digit = self.calculate_check_digit(idcard)
            idcard += check_digit

        # 校验18位身份证号
        if len(idcard) != 18 or not re.match(r'^\d{17}[\dX]$', idcard):
            return '错误：身份证号码格式不正确'

        # 获取出生日期
        birthdate = idcard[6:14]

        # 获取性别
        gender_code = int(idcard[16])
        gender = ''
        if gender_code % 2 == 0:
            gender = '女'
        else:
            gender = '男'

        # 校验出生日期合法性
        year = int(birthdate[:4])
        month = int(birthdate[4:6])
        day = int(birthdate[6:])
        if year < 1900 or month > 12 or day > 31:
            return '错误：出生日期不合法'

        # 获取出生地
        # TODO: 根据身份证号码解析出生地

        return f'身份证号码合法。出生日期：{birthdate}，性别：{gender}，出生地：'


              
    

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()点击校验后出现not found