import 'dart:io';

import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/utils/image_load.dart';
import 'package:account_center/page/account_company/company_auth/widget/common/gesture_tap.dart';
import 'package:account_center/page/enterprise/join_or_new_enterprise_page/enterprise_proxy_person_page/clx_file_manage.dart';
import 'package:account_center/widget/select_image_utils.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

import 'enterprise_proxy_person_state.dart';

class EnterpriseProxyPersonLogic extends GetxController {
  final EnterpriseProxyPersonState state = EnterpriseProxyPersonState();
  dynamic data;

  String get fileName => data?['confirmationFileName'] ?? '';

  String templateUrl = '';

  @override
  void onInit() {
    super.onInit();
    _requestTemplate();
    data = Get.arguments['proxyInfo'];
    if (data != null) {
      state.controllerName.text = data['agentName'] ?? '';
      state.controllerPhone.text = data['agentMobile'] ?? '';
      state.controllerIDCard.text = data['agentCardNo'] ?? '';
      state.cardUrlUpPath = data['agentCardFrontImg'] ?? '';
      state.cardUrlDownPath = data['agentCardBackImg'] ?? '';
    }
  }

  void completed() {
    /* if (state.controllerName.text.isEmpty) {
      ToastUtil.showToast('请填写姓名');
      return;
    }
    if (state.controllerPhone.text.isEmpty) {
      ToastUtil.showToast('请填写手机号');
      return;
    }
    if (state.controllerIDCard.text.isEmpty) {
      ToastUtil.showToast('请填写身份证号');
      return;
    }
    if (state.cardUrlUpPath.isNullOrEmpty()) {
      ToastUtil.showToast('请上传身份证正面');
      return;
    }
    if (state.cardUrlDownPath.isNullOrEmpty()) {
      ToastUtil.showToast('请上传身份证国徽面');
      return;
    }*/
    backResult();
  }

  void backResult() {
    Map<String, dynamic> params = {
      'agentName': state.controllerName.text,
      'agentMobile': state.controllerPhone.text,
      'agentCardNo': state.controllerIDCard.text,
      'agentCardFrontImg': state.cardUrlUpPath, //身份证正面
      'agentCardBackImg': state.cardUrlDownPath,
      'confirmationFileName': fileName,
      'agentConfirmation': data?['agentConfirmation'],
    };
    unFocus();
    Get.back(result: params);
  }

  void unFocus() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  void cameraCapture(bool isUp) {
    selectPicType(onSuccess: (data) {
      if (isUp) {
        state.cardUrlUpPath = data;
      } else {
        state.cardUrlDownPath = data;
      }
      update();
    });
  }

  void delete(bool isUp) {
    if (isUp) {
      state.cardUrlUpPath = null;
    } else {
      state.cardUrlDownPath = null;
    }
    update();
  }

  void selectFile() {
    Get.bottomSheet(Container(
      height: 420,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Color(0xFFE6EBF9),
            Color(0xFFF3F5F9),
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(top: 20, left: 20, right: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '企业注册确认函',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF222222),
                  ),
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '请下载模版文件，填写信息并盖章上传\n支持 pdf、jpg、png、jpeg',
                        style: TextStyle(
                          color: Color(0xFF727994),
                          fontSize: 13,
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 20,
                    ),
                    GestureTapWidget(
                      onTap: downLoadTemplate,
                      child: Container(
                        padding:
                            EdgeInsets.symmetric(vertical: 8, horizontal: 15),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Color(0xFFC3CCD9),
                            width: 1,
                          ),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          '下载模版',
                          style: TextStyle(
                            color: Color(0xFF707070),
                            fontSize: 15,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    )
                  ],
                )
              ],
            ),
          ),
          SizedBox(height: 10),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                color: Color(0xFFF3F5F8),
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(20),
                ),
              ),
              padding: EdgeInsets.all(20),
              child: Column(
                children: [
                  item('上传图片', 'ic_image', () {
                    _selectPic(true);
                  }),
                  SizedBox(height: 10),
                  item('上传附件', 'ic_pdf', () {
                    _selectPic(false);
                  })
                ],
              ),
            ),
          )
        ],
      ),
    ));
  }

  Widget item(String title, String icon, Function() onTap) {
    return GestureTapWidget(
      onTap: onTap,
      child: Container(
          height: 70,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            color: Colors.white,
          ),
          padding: EdgeInsets.symmetric(horizontal: 20),
          child: Row(
            children: [
              ImageLoad.loadAssertImage(
                icon,
                width: 25,
                height: 30,
              ),
              SizedBox(
                width: 12,
              ),
              Text(
                title,
                style: TextStyle(
                    fontSize: 18,
                    color: Color(0xFF344254),
                    fontWeight: FontWeight.w500),
              ),
              Spacer(),
              Icon(
                Icons.arrow_forward_ios,
                size: 16,
                color: Color(0xffA4A8B1),
              ),
            ],
          )),
    );
  }

  Future<void> requestStoragePermission() async {
    PermissionStatus status;
    var device = await getDeviceInfo();
    if (Platform.isAndroid &&
        (device.systemVersion.contains('14') ||
            device.systemVersion.contains('13'))) {
      // status = await Permission.manageExternalStorage.request();
      return;
    } else {
      status = await Permission.storage.request();
    }
    if (!status.isGranted) {
      ToastUtil.showToast('请开启文件存储权限！');
      throw Exception('用户未授予存储权限');
    }
  }

  void downLoadTemplate() async {
    if (Platform.isIOS) {
      CLXFileManage.downloads(ossDomain + templateUrl).then((value) {
        ToastUtil.showToast(value);
      });
    } else {
      await requestStoragePermission();
      var savePath = await getFilePath();
      savePath = '$savePath/${path.basename(templateUrl)}';
      // print(savePath);
      File file = File(savePath);
      if (await file.exists()) {
        copyToPublic(savePath);
        return;
      }
      LoadingUtils.showLoading();
      bool isSuccess = await download(ossDomain + templateUrl, savePath);
      LoadingUtils.dismiss();
      if (isSuccess) {
        copyToPublic(savePath);
      } else {
        ToastUtil.showToast('下载失败');
      }
    }
  }

  void copyToPublic(String savePath) {
    try {
      CLXFileManage.copyFileToPublic(savePath, title: '企业注册确认函').then((value) {
        ToastUtil.showToast('下载成功,文件已保存至系统文件夹');
      });
    } catch (e) {
      ToastUtil.showToast('下载失败');
    }
  }

  Future<String?> getFilePath() async {
    var dir = await getApplicationCacheDirectory();
    return dir.path;
  }

  void _requestTemplate() {
    fetch(Method.get,
        url: '/msl-user/companyAuth/getCompanyAgentConfirmationTemplate',
        onSuccess: (response) {
      templateUrl = response;
    });
  }

  void _selectPic(bool isPic) async {
    String? filePath;
    if (isPic) {
      XFile? file = await ImagePicker()
          .pickImage(source: ImageSource.gallery, imageQuality: 20);
      if (file != null) {
        filePath = file.path;
      }
    } else {
      FilePickerResult? result = await FilePicker.platform
          .pickFiles(allowedExtensions: ['pdf'], type: FileType.custom);
      if (result != null) {
        filePath = result.files.single.path;
        if (filePath?.endsWith('pdf') != true) {
          ToastUtil.showToast('仅支持pdf类型文件');
          return;
        }
      }
    }
    if (filePath != null) {
      LoadingUtils.showLoading();
      var fileUrl = await uploadFile(path: filePath);
      ToastUtil.showToast('上传成功');
      data?['confirmationFileName'] = path.basename(fileUrl);
      data?['agentConfirmation'] = fileUrl;
      Get.back();
      update();
    }
  }
}
