package service

import (
	"encoding/json"
	"fmt"
	"kpt.xdmy/apiserver/config"
	"time"

	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"

	_ "github.com/go-sql-driver/mysql"

	"kpt.xdmy/apiserver/model"
	"kpt.xdmy/apiserver/model/http"
)

var supplierChan chan error

// 定时 从sap拉取供应商数据
// 预留参数;时间、编码,提供给手动调用接口
func (s *Service) SapSupplier(t time.Time, code string, pastureid int) {
	supplierChan = make(chan error, 10)
	r := new(http.SupplierReq)
	rp := new(http.SupplierResp)
	var e error
	r.Dest.DestID = "EQMAN"
	r.Dest.BussTp = "MM004"
	//r.Dest.Url = "http://192.168.61.117/SAPP0/Common/MM004/QuerySupplier/"
	r.Dest.Url = fmt.Sprintf("%s/Common/MM004/QuerySupplier/", config.Conf.Http.Routing)

	if t.IsZero() {
		t = time.Now()
	}
	r.Data.BudatB = t.Format("20060102")
	r.Data.BudatE = t.Format("20060102")
	//r.Data.BudatB = "20221004"
	//r.Data.BudatE = "20221022"
	//r.Data.CompanyCode = "1004"
	r.Data.CompanyCode = code
	r.Data.Types = []http.ZSORT{{Type: "设备"}, {Type: "服务类"}, {Type: "备品备件类"}, {Type: "工程类"}, {Type: "其他类"}}

	rbyte, _ := json.Marshal(r)
	fmt.Println(string(rbyte))
	if e = s.SyncSap(r, rp, rbyte); e == nil {
		if rp.Dest.Status == "S" {
			log.Infof("sap  supplier success :  mlen=%d", len(rp.Data.Master))
		} else {
			e = errors.Errorf("sap  supplier fail: %s", rp.Dest.MessText)
		}
	} else {
		e = errors.Wrap(e, "sap supplier error:")
	}
	var update error
	var count int
	for _, v := range rp.Data.Master {
		update = nil
		s.updateProvider(&v)
		update = <-supplierChan
		if update != nil {
			log.Error(update)
			count++
			l := model.SapDetailLog{Name: "supplier", Code: v.Code, ErrorText: update.Error()}
			if e := s.d.DB.Create(&l); e != nil {
				log.Errorf("add sapdetail log: %v", e)
			}
		}
		// break
	}
	if e != nil {
		log.Error(e)
	} else if update != nil {
		e = errors.Errorf("supplier update fail sum:%d", count)
	} else {
		log.Infof("supplier update success sum:%d", len(rp.Data.Master)-count)
	}
	s.AddSapLog(r, e)
	return
}

// 更新供应商
func (s *Service) updateProvider(sup *http.Supplier) {
	pv := new(model.Provider)

	if len(sup.UpDate) == 8 {
		sup.UpDate = sup.UpDate[:4] + "-" + sup.UpDate[4:6] + "-" + sup.UpDate[6:]
	}
	if len(sup.UpTime) == 6 {
		sup.UpTime = sup.UpTime[:2] + ":" + sup.UpTime[2:4] + ":" + sup.UpTime[4:]
	}
	if sup.UpTime != "" {
		sup.UpDate = sup.UpDate + " " + sup.UpTime
	}
	if t, e := time.Parse("2006-01-02 15:04:05", sup.UpDate); e != nil {
		supplierChan <- errors.Errorf("time parse  : %s, %s", sup.UpDate)
	} else {
		pv.ModifyTime = t
	}
	pv.ProviderIntro = sup.Name
	pv.ProviderName = sup.ShortName
	pv.ProviderNumber = sup.Code
	pv.CompanyCode = sup.CompanyCode
	pv.SortName = sup.ZSORT
	pv.Linkman = sup.Contact
	pv.Email = sup.Mail
	pv.Telphone = sup.Phone
	pv.SapCode = sup.Code
	if sup.Dflag == "" {
		pv.Enable = 1
	}
	fmt.Println(pv)
	if e := s.d.DB.Where(model.Provider{SapCode: sup.Code}).Assign(pv).FirstOrCreate(&pv).Error; e != nil {
		supplierChan <- errors.Wrapf(e, "provider update  failed:code =%s", sup.Code)
	} else {
		log.Infof("provider update succeeded:%s,%s,%s", sup.Code, sup.ShortName, sup.CompanyCode)
		supplierChan <- nil
	}
}