let system = require("../../../system")
const http = require("http")
const fs = require("fs")
let xlsx = require('node-xlsx').default;
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.excelName = p.search.name;
            if (p.search.code)
                query.actionBody.code = p.search.code;
            if (p.search.tm_applier)
                query.actionBody.tm_applier = p.search.tm_applier;
            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.publish_status)
                query.actionBody.publish_status = p.search.publish_status;
            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/querypublish 检索发布
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * [{"name":"商标名称","code":"商标申请号","business_quoted_price":"底价","contacts":"联系人","mobile":"手机号"}]
     * @apiSuccessExample {json} 成功示例:
     * {"status":0,"msg":"","data":[],"bizmsg":"empty","requestId":""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async querypublish(p, q, req) {
        let body = {
            "actionType": "tmBatchUpload",
            "actionBody": {
                "tm": p.data
            }
        };
        let rtn = await this.execClient.execPost(body, tmurl);
        let data = JSON.parse(rtn.stdout);
        if (data.status == 1) {
            let tradedb = [];
            data.data.tm.map(db => tradedb.push({
                opath: p.opath,
                user_id: p.userid,
                company_id: p.company_id,
                trademark_id: db.id,
                type:p.data.type,
                reason:p.data.reason,
                tm_code: db.code
            }));
            rtn = await this.service.bulkCreate(tradedb);
        }
        return system.getResult(rtn)
    }

    /**
     * @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 = {
                "actionType": "tmBatchUpload",
                "actionBody": {
                    "tm": p.data
                }
            };
            let uploadid;
            if (q && q.upload_id) {
                uploadid = q.upload_id;
                body.upload_id = uploadid;
            }
            let rtn = await this.execClient.execPost(body, pushurl);
            console.log("=====================>批量发布返回", rtn);
            let data = JSON.parse(rtn.stdout);
            if (data.status == 1) {
                let tradedb = [];
                this.notify({
                    actionBody: {
                        resultInfo: {
                            data: data.data
                        },
                        messageBody: {
                            upload_id:uploadid
                        }
                    }
                },q,req)
                p.data.map(db => tradedb.push({
                    opath: p.opath,
                    user_id: p.userid,
                    company_id: p.company_id,
                    // trademark_id: db.id,
                    type:p.data.type,
                    reason:p.data.reason,
                    tm_code: db.code,
                    upload_id: uploadid
                }));
                await this.service.bulkCreate(tradedb);
            }
            return system.getResultSuccess()
        } catch (e) {
            return system.getResultFail(-2, e)
        }
    }

    //接受队列消息，解析excel
    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
        });
        if (upload.status == 1)
            return {
                status: 1,
                msg: "ok"
            }
        let sp = fileurl.split("/");
        let filename = sp[sp.length - 1];
        await this.restClient.execDownload(fileurl, filename);
        let list = xlsx.parse(filename);
        let data = [];
        list[0].data.shift();
        list[0].data.forEach(item => {
            if (item.length > 0) {
                data.push({
                    name: item[0],
                    code: item[1],
                    business_quoted_price: item[2],
                    contacts: item[3],
                    mobile: item[4],
                    type: item[5],
                    reason: item[6],
                })
            }
        });
        if (fs.existsSync(filename)) {
            fs.unlinkSync(filename);
        }
        upload.total = data.length;
        await upload.save();
        let pros = []
        for (let i = 0; i < data.length; i += 20) {
            let item = data.slice(i, i + 20);
            item.forEach(e => {
                e.channel_code = p.actionBody.company_id;
                e.channel_name = p.actionBody.channel_name;
            });
            let pushd = {
                data: item
            };
            pushd.opath = p.actionBody.opath;
            pushd.userid = p.actionBody.userid;
            pushd.company_id = p.actionBody.company_id;
            pushd.channel_name = p.actionBody.channel_name;
            pros.push(this.publish(pushd, {upload_id: uploadid}))
        }
        await Promise.all(pros)
        return {
            status: 1,
            msg: "ok"
        }
    }

    /**
     * @api {post} /web/trademark/trademarkCtl/excelpublish 上传excel
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"file_url": "","name":""}
     * @apiSuccessExample {json} 成功示例:
     * {"success": ""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async excelpublish(p, q, req) {
        try {
            let upload = await this.uploadSve.create({
                name: p.name,
                file_url: p.file_url
            });
            this.process({actionBody:{
                    upload_id: upload.id,
                    file_url: p.file_url,
                    opath: p.opath,
                    userid: p.userid,
                    channel_name: p.channel_name,
                    company_id: p.company_id
                },q,req})
            return system.getResultSuccess(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/updatestatus 修改状态
     * @apiDescription (下架/审核/状态修改)
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"data": [ {"id":1,"code":1,"platform_quoted_price":1200}],status:"uppershelf/lowershelf"}
     * @apiSuccessExample {json} 成功示例:
     * {"success": ""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async updatestatus(p, q, req) {
        let body = {
            "actionType": "tmStatusUpdate",
            "actionBody": {
                tm: p.data,
                status: p.status
            }
        };
        let rtn = await this.execClient.execPost(body, tmurl);
        let data = JSON.parse(rtn.stdout);
        return data
    }

    /**
     * @api {post} /web/trademark/trademarkctl/updatestrademarktype 修改商标类型
     * @apiGroup 标源管理
     * @apiParamExample {json} 请求参数
     * {"data": [ {"id":1,"trademark_type":1]}
     * @apiSuccessExample {json} 成功示例:
     * {"success": ""}
     * @apiErrorExample {json} 失败示例:
     * {"error": ""}
     */
    async updatestrademarktype(p, q, req) {
        let body = {
            "actionType": "tmTrademarkTypeUpdate",
            "actionBody": p.data
        };
        let rtn = await this.execClient.execPost(body, tmurl);
        let data = JSON.parse(rtn.stdout);
        return 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 += p.actionBody.resultInfo.data.failCount || 0;
            if (upload.total <= upload.success + upload.fail)
                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 {
            status: 1,
            msg: "ok"
        }
    }
}

module.exports = TrademarkCtl;

