let system = require("../../../system")
const http = require("http")
const fs = require("fs")
const XLSX = require('xlsx')
const querystring = require('querystring');
let settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const tmtransactionPath = "/tmtransaction/action/trademarktransaction/springBoard";
const tmurl = settings.tmtransactionurl() + tmtransactionPath;
let pushClient = require("../../../utils/totxClient.js").trademark;
let notifyurl = settings.serviceurl() + "/web/trademark/trademarkCtl/notify";
let pushmyurl = settings.serviceurl() + "/web/trademark/trademarkCtl/process";
let pushurl = settings.tmtransactionurl() + "/tmtransaction/action/trademarktransaction/springBoard";

//标源管理
class TrademarkCtl extends CtlBase {
    constructor() {
        super("trademark", CtlBase.getServiceName(TrademarkCtl));
        this.uploadSve = system.getObject("service.trademark.uploadSve");
        this.execClient = system.getObject("util.execClient");
        this.restClient = system.getObject("util.restClient");
    }

    /**
     * @api {post} /web/trademark/trademarkctl/findAndCountAll 获取列表
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"pageInfo": {"pageNo":1,"pageSize":10}}
     * @apiSuccessExample {json} 成功示例:
     * {"status":0,"msg":""data":{"results":{"rows":[]}}}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async findAndCountAll(p, q, req) {
        let query = {
            "actionType": "tmInfo",
            "actionBody": {
                channel_code: p.company_id,
                pageSize: p.pageInfo.pageSize,// 每页数量
                pageNumber: p.pageInfo.pageNo,// 页
            }
        };
        if (p.search) {
            if (p.search.name)
                query.actionBody.name = p.search.name;
            if (p.search.code)
                query.actionBody.code = p.search.code;
            if (p.search.channel_name)
                query.actionBody.name = p.search.channel_name;
            if (p.search.tm_start_day)
                query.actionBody.tm_start_day = p.search.tm_start_day;
            if (p.search.tm_end_day)
                query.actionBody.tm_end_day = p.search.tm_end_day;
            if (p.search.ids)
                query.actionBody.tmList = p.search.ids;
        }
        let rtn = await this.execClient.execPost(query, tmurl);
        let data = JSON.parse(rtn.stdout);
        return system.getResultList(data.totalCount, data.data || [])
    }

    /**
     * @api {post} /web/trademark/trademarkctl/findOne 获取详情
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"id": "1"}
     * @apiSuccessExample {json} 成功示例:
     * {"success": ""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async findOne(p, q, req) {
        let body = {
            "actionType": "tmDetail",
            "actionBody": {
                tmId: 0
            }
        };
        body.actionBody.tmId = p.id;
        let rtn = await this.execClient.execPost(body, tmurl);
        let data = JSON.parse(rtn.stdout);
        return system.getResultSuccess(data.data)
    }

    /**
     * @api {post} /web/trademark/trademarkctl/publish 批量发布
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * [{"name":"商标名称","code":"商标申请号","business_quoted_price":"底价","contacts":"联系人","mobile":"手机号"}]
     * @apiSuccessExample {json} 成功示例:
     * {"status":0,"msg":"","data":[],"bizmsg":"empty","requestId":""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async publish(p, q, req) {
        try {
            let body = {
                "tm": p
            };
            let uploadid;
            if (q && q.upload_id) {
                uploadid = q.upload_id;
                body.upload_id = uploadid;
            }
            let rtn = await pushClient(body, pushurl, notifyurl);
            if (rtn.status == 1) {
                let tradedb = [];
                p.map(db => tradedb.push({
                    opath: p.opath,
                    user_id: p.userid,
                    company_id: p.company_id,
                    // trademark_id: db.id,
                    tm_code: db.code,
                    upload_id: uploadid
                }));
                rtn = await this.service.bulkCreate(tradedb);
            }
            return system.getResult(rtn)
        } catch (e) {
            return system.getResultFail(-2, e)
        }
    }

    async process(p, q, req) {
        let fileurl = p.actionBody.file_url;
        let uploadid = p.actionBody.upload_id;
        let upload = await this.uploadSve.findOne({
            id: uploadid
        });
        let sp = fileurl.split("/");
        let filename = sp[sp.length - 1];
        await this.restClient.execDownload(fileurl, filename);
        let csv = fs.readFileSync(filename).toString();
        let ec = csv.replace("商标名称（必填）", "name")
            .replace("申请号（必填）", "code")
            .replace("卖家底价（必填，仅填入数字，如5500、12800）", "business_quoted_price")
            .replace("卖家姓名（必填）", "contacts").replace("卖家电话（必填）", "mobile");
        const workbook = XLSX.read(ec, {type: 'binary'});
        const wsName = workbook.SheetNames[0];//取第一张表
        let data = XLSX.utils.sheet_to_json(workbook.Sheets[wsName]);//生成json表格内容
        if (fs.existsSync(filename)) {
            fs.unlinkSync(filename);
        }
        upload.total = data.length;
        await upload.save();
        for (let i = 0; i < data.length; i += 200) {
            let pushd = data.slice(i, i + 200);
            pushd.opath = p.actionBody.opath;
            pushd.user_id = p.actionBody.user_id;
            pushd.company_id = p.actionBody.company_id;
            await this.publish(pushd, {upload_id: uploadid})
        }
        return system.getResult(1, "ok")
    }

    async excelpublish(p, q, req) {
        try {
            let upload = await this.uploadSve.create({
                name: p.name,
                file_url: p.file_url
            });
            let rtn = await pushClient({
                upload_id: upload.id,
                file_url: p.file_url,
                opath: p.opath,
                user_id: p.userid,
                company_id: p.company_id
            }, pushmyurl);
            if (rtn.status == 1) {
                return system.getResult(rtn)
            }
            return system.getResultFail(-1, rtn.msg, rtn)
        } catch (e) {
            return system.getResultFail(-2, e)
        }
    }

    /**
     * @api {post} /web/trademark/trademarkctl/update 修改
     * @apiDescription (下架/审核/状态修改)
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"id": "1"}
     * @apiSuccessExample {json} 成功示例:
     * {"success": ""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async update(p, q, req) {
        let body = {
            "actionType": "tmInfoUpdate",
            "actionBody": p
        };
        let rtn = await this.execClient.execPost(body, tmurl);
        let data = JSON.parse(rtn.stdout);
        return system.getResult(data.data)
    }

    /**
     * @api {post} /web/trademark/trademarkCtl/delete 删除
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"id": "1"}
     * @apiSuccessExample {json} 成功示例:
     * {"success": ""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async delete(p, q, req) {
        let body = {
            "actionType": "tmInfoDelete",
            "actionBody": {
                id: 0
            }
        };
        body.actionBody.id = p.id;
        let rtn = await this.execClient.execPost(body, tmurl);
        let data = JSON.parse(rtn.stdout);
        if (data.status == 1) {
            let en = await this.service.findOne({trademark_id: p.id});
            if (en != null) {
                en.destroy();
            }
        }
        return system.getResult(data.data)
    }

    //接受队列返回消息
    async notify(p, q, req) {
        console.log("=====================>接受队列消息", p);
        let upload_id = p.actionBody.messageBody.upload_id;
        if (upload_id) {//excel上传人物更新任务数据
            let upload = await this.uploadSve.findOne({
                id: upload_id
            });
            upload.success += p.actionBody.resultInfo.data.successCount || 0;
            upload.fail = upload.total - p.actionBody.resultInfo.data.successCount || 0;
            upload.status = 1;
            await upload.save();
        }
        let tradedb = p.actionBody.resultInfo.data.tm;
        tradedb.map(async db => {
            await this.service.dao.model.update({
                trademark_id: db.id,
                tm_code: db.code
            }, {where: {tm_code: db.code}});
        });
        return system.getResult(1,"ok")
    }

    async getidlist(p, q, req) {
        let list = await  this.service.findAll({upload_id: p.upload_id});
        return system.getResult(list)
    }
}

module.exports = TrademarkCtl;

