package com.eitc.manage.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eitc.common.annotation.Anonymous;
import com.eitc.common.annotation.InterfaceVerification;
import com.eitc.common.annotation.Log;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.core.domain.AjaxResult;
import com.eitc.common.core.page.TableDataInfo;
import com.eitc.common.enums.BusinessType;
import com.eitc.common.utils.CommonUtils;
import com.eitc.manage.controller.helper.SysClinicInfoHelper;
import com.eitc.manage.domain.SysClinicInfo;
import com.eitc.manage.service.ISysClinicInfoService;
import com.eitc.manage.utils.NetworkUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;










/**
 * @date: 2024/05/17 15:51
 */
@Api(tags = "系统诊所信息的控制层")
@RestController
@RequestMapping("/sys/clinict")
public class SysClinicInfoController extends BaseController {

    @Autowired
    private ISysClinicInfoService sysClinicInfoService;
    @Autowired
    private SysClinicInfoHelper sysClinicInfoHelper;
    @Autowired
    private HttpServletRequest request;

    /**
     *  诊所列表查询
     * @param info
     * @return
     */

//    @PreAuthorize("@ss.hasPermi('system:clinict:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysClinicInfo info) {
        startPage();
        List<SysClinicInfo> list = sysClinicInfoService.list(Wrappers.<SysClinicInfo>lambdaQuery()
                .like(info.getClinicName()!=null,SysClinicInfo::getClinicName, info.getClinicName())
        );
        return getDataTable(list);
    }


    /**
     * 新增诊所
     */
    @PreAuthorize("@ss.hasPermi('system:clinict:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@Validated @RequestBody SysClinicInfo info) {
        String code = sysClinicInfoHelper.getSysClinicInfoCode();
        info.setClinicCode(code);
        if (info.getVersionRepair() == null)
        info.setVersionRepair(info.getVersionInfo());
        return toAjax(sysClinicInfoService.save(info));
    }

    /**
     * 修改诊所
     */
    @PreAuthorize("@ss.hasPermi('system:clinict:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("edit")
    public AjaxResult edit(@Validated @RequestBody SysClinicInfo info) {
        return toAjax(sysClinicInfoService.updateById(info));
    }

    /**
     * 删除诊所
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id) {
        return toAjax(sysClinicInfoService.removeById(id));
    }


    /**
     * APP查询诊所列表
     * @return
     */

    @InterfaceVerification
    @Anonymous
    @GetMapping("/appGetClinictList")
    public AjaxResult appGetClinictList() {
        return success(sysClinicInfoService.list());
    }


//    @InterfaceVerification

    /**
     * 提供查询履约信息，并且校验
     * @param response
     */
    @GetMapping("/getClinictListInfo")
    @Anonymous
    @InterfaceVerification
    public AjaxResult getClinictListInfo(HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ipAddress = NetworkUtils.getIpAddress(request);
        System.out.println(ipAddress + "ipAddress");
        List<SysClinicInfo> list = sysClinicInfoService.list(Wrappers.<SysClinicInfo>lambdaQuery()
                .eq(SysClinicInfo::getClinicIp, ipAddress)
        );
        if (list.isEmpty())
            throw new RuntimeException("诊所信息校验有误，请联系管理员！");
        SysClinicInfo clinicInfo = list.get(0);
        // 时间校验
        int compared = new Date().compareTo(clinicInfo.getExpireTime());
        if (compared >= 0) {
            response.addHeader("msg", "1");
        } else {
            response.addHeader("msg", "2");
        }
        response.addHeader("phone", list.get(0).getPhone());
        response.addHeader("versionRefer", CommonUtils.toUnicode(list.get(0).getVersionRefer()));
        response.addHeader("creatTime", sdf.format(list.get(0).getCreatTime()));
        response.addHeader("quota", list.get(0).getQuota());
        response.addHeader("expireTime", sdf.format(list.get(0).getExpireTime()));
        response.addHeader("address", list.get(0).getAddress());
        response.addHeader("versionInfo", list.get(0).getVersionInfo());
        response.addHeader("versionRepair", list.get(0).getVersionRepair());
        response.addHeader("statusInt", list.get(0).getStatusInt());
        return success();
    }

    /**
     * 下载文件
     * @param version
     * @param response
     * @throws IOException
     */
    @GetMapping("downloadLocal")
    @Anonymous
    @InterfaceVerification
    public void downloadLocal(Integer version, HttpServletResponse response) throws IOException {
        // 清空response
        String ipAddress = NetworkUtils.getIpAddress(request);
        System.out.println(ipAddress+"ipAddress");
//        String version = pullDecrypt(ciphertext, key,response);
//        List<SysClinicInfo> list = sysClinicInfoService.list(Wrappers.<SysClinicInfo>lambdaQuery()
//                .eq(SysClinicInfo::getClinicIp, ipAddress)
//        );
        List<SysClinicInfo> list = sysClinicInfoService.list(Wrappers.<SysClinicInfo>lambdaQuery()
                .eq(SysClinicInfo::getClinicIp, "127.0.0.1")
        );
        if (list.isEmpty())
//            response.addHeader("msg","2");
            throw new RuntimeException("诊所信息校验有误，请联系管理员！");

        SysClinicInfo clinicInfo = list.get(0);
        response.reset();
        sysClinicInfoHelper.fileStream(response, clinicInfo,version);
    }




    /**
     * 升级文件上传
     *
     * @return
     */
    @PostMapping("/upgradeFileUpload")
    public AjaxResult upgradeFileUpload(@RequestParam("file") MultipartFile file
            , @RequestParam("id") String id
            , @RequestParam("version") String version
    ) throws IOException, NoSuchAlgorithmException {
        // 生成一个唯一的文件名
        sysClinicInfoHelper.upgradeFileUpload(file, id, version);
        return success();
    }


}
