package com.reg.server.registration;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.core.net.URLEncodeUtil;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import com.aliyun.tea.TeaException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/registrations")
@CrossOrigin
public class RegistrationController {
    private final RegistrationService service;

    /**
     * <b>description</b> :
     * <p>使用凭据初始化账号Client</p>
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        config.setAccessKeyId("LTAI5tSqZrdsoC54tgWTrdYB");
        config.setAccessKeySecret("I1nu7T6DJuvhribphaWh53RRw8TdC7");
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public RegistrationController(RegistrationService service) {
        this.service = service;
    }

    @GetMapping
    public List<Registration> list() {
        return service.list();
    }

    @GetMapping("/search")
    public List<Registration> search(
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String contact,
            @RequestParam(required = false) String serviceType,
            @RequestParam(required = false) String powerType,
            @RequestParam(required = false) String status) {
        Registration condition = new Registration();
        condition.setCustomerName(customerName);
        condition.setContact(contact);
        condition.setServiceType(serviceType);
        condition.setPowerType(powerType);
        condition.setStatus(status);
        RandomUtil.randomString(8);
        return service.search(condition);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Registration> get(@PathVariable Long id) {
        return service.get(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Registration> create(@RequestBody Registration registration) {
        Registration saved = service.create(registration);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> update(@PathVariable Long id, @RequestBody Registration registration) {
        String urlPath = null;
        if ("已登记".equals(registration.getStatus().trim()) && registration.getFileName() != null) {
            urlPath = RandomUtil.randomString(5);
            registration.setUrlPath(urlPath);
            // 发送短信通知
            String smsUrl = "http://172.27.77.221:8060/send";

            String text = "【国家电网】尊敬的" + registration.getCustomerName() + "，感谢您的支持！您咨询的业务办理详情可点击：" + "http://192.168.32.24:8080/#/getfile/"+urlPath+"查阅。";
            String fullUrl = smsUrl + "?password=1&recipient=" + registration.getContact() + "&text=" + URLEncodeUtil.encode(text) + "&encoding=U";
            String response = HttpUtil.get(fullUrl);
            // 解析 XML 响应
            try {
                XPathFactory xPathFactory = XPathFactory.newInstance();
                XPath xpath = xPathFactory.newXPath();
                javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
                javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
                org.w3c.dom.Document doc = builder.parse(new org.xml.sax.InputSource(new java.io.StringReader(response)));
                String error = xpath.evaluate("//send/error/text()", doc);
                if (!"0".equals(error)) {
                    throw new Exception("短信发送失败！状态码：" + error);
                }
                String messageStatus = xpath.evaluate("//send/message_status/text()", doc);
                String msgId = xpath.evaluate("//send/msg_id/text()", doc);
                System.out.println("短信发送结果 error=" + error + ", message_status=" + messageStatus + "msgId=" + msgId);
                registration.setMsgId(msgId);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseEntity.badRequest().build();
            }
        }
        boolean updated = service.update(id, registration);
        return updated ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        boolean deleted = service.delete(id);
        return deleted ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build();
    }


    @GetMapping("/getPdfPath/{urlPath}")
    public ResponseEntity<String> getPdfPath(@PathVariable String urlPath) {
        List<Registration> search = service.search(new Registration() {{
            setUrlPath(urlPath);
        }});
        if (search == null || search.isEmpty()) {
            return ResponseEntity.ok("");
        }
        return ResponseEntity.ok(search.get(0).getFileName());
    }


//	@GetMapping("sendSms/{id}")
//	public ResponseEntity sendSms (@PathVariable Long id) throws Exception {
//		com.aliyun.dysmsapi20170525.Client client = this.createClient();
//		com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest();
//		Registration registration = service.get(id)
//				.orElseThrow(() -> new IllegalStateException("数据不可能为空，id=" + id));
//		sendSmsRequest.setPhoneNumbers(registration.getContact());
//		sendSmsRequest.setSignName("顷琦");
//		sendSmsRequest.setTemplateCode("SMS_499300449");
//		com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
//		try {
//			com.aliyun.dysmsapi20170525.models.SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
//			System.out.println(new com.google.gson.Gson().toJson(resp));
//		} catch (TeaException error) {
//			System.out.println(error.getMessage());
//			System.out.println(error.getData().get("Recommend"));
//		} catch (Exception _error) {
//			TeaException error = new TeaException(_error.getMessage(), _error);
//			System.out.println(error.getMessage());
//			System.out.println(error.getData().get("Recommend"));
//
//		}
//		return ResponseEntity.status(HttpStatus.OK).body("发送短信成功");
//    }
}
