question.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package learning
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "lims_adapter/dao/learning"
  9. "lims_adapter/model/learning"
  10. "net/http"
  11. "strconv"
  12. "strings"
  13. "dashoo.cn/micro_libary/micro_srv"
  14. "dashoo.cn/micro_libary/myerrors"
  15. "dashoo.cn/micro_libary/request"
  16. "github.com/gogf/gf/os/gtime"
  17. "github.com/gogf/gf/util/gvalid"
  18. "github.com/xuri/excelize/v2"
  19. )
  20. type LearningQuestionService struct {
  21. Dao *dao.LearningQuestionDao
  22. Tenant string
  23. userInfo request.UserInfo
  24. }
  25. func NewLearningQuestionService(ctx context.Context) (*LearningQuestionService, error) {
  26. tenant, err := micro_srv.GetTenant(ctx)
  27. if err != nil {
  28. return nil, fmt.Errorf("获取组合码异常:%s", err.Error())
  29. }
  30. // 获取用户信息
  31. userInfo, err := micro_srv.GetUserInfo(ctx)
  32. if err != nil {
  33. return nil, fmt.Errorf("获取用户信息异常:%s", err.Error())
  34. }
  35. return &LearningQuestionService{
  36. Dao: dao.NewLearningQuestionDao(tenant),
  37. Tenant: tenant,
  38. userInfo: userInfo,
  39. }, nil
  40. }
  41. func (s LearningQuestionService) Get(ctx context.Context, req *learning.LearningQuestionGetReq) (ent *learning.LearningQuestionGetRsp, err error) {
  42. validErr := gvalid.CheckStruct(ctx, req, nil)
  43. if validErr != nil {
  44. return nil, myerrors.NewMsgError(nil, validErr.Current().Error())
  45. }
  46. q, err := s.Dao.Where("Id = ?", req.Id).One()
  47. if err != nil {
  48. return nil, err
  49. }
  50. if q == nil {
  51. return nil, myerrors.NewMsgError(nil, "题目不存在")
  52. }
  53. content := []learning.LearningQuestionOption{}
  54. err = json.Unmarshal([]byte(q.Content), &content)
  55. return &learning.LearningQuestionGetRsp{
  56. LearningQuestion: *q,
  57. Content: content,
  58. }, err
  59. }
  60. func (s LearningQuestionService) List(ctx context.Context, req *learning.LearningQuestionListReq) (int, []*learning.LearningQuestionGetRsp, error) {
  61. dao := &s.Dao.LearningQuestionDao
  62. if req.Name != "" {
  63. dao = dao.Where("Name LIKE ?", fmt.Sprintf("%%%s%%", req.Name))
  64. }
  65. if req.SkillId != 0 {
  66. dao = dao.Where("SkillId = ?", req.SkillId)
  67. }
  68. total, err := dao.Count()
  69. if err != nil {
  70. return 0, nil, err
  71. }
  72. if req.Page != nil {
  73. if req.Page.Current == 0 {
  74. req.Page.Current = 1
  75. }
  76. if req.Page.Size == 0 {
  77. req.Page.Size = 10
  78. }
  79. dao = dao.Page(req.Page.Current, req.Page.Size)
  80. }
  81. if req.OrderBy != nil && req.OrderBy.Value != "" {
  82. order := "asc"
  83. if req.OrderBy.Type == "desc" {
  84. order = "desc"
  85. }
  86. dao = dao.Order(req.OrderBy.Value, order)
  87. }
  88. ent, err := dao.All()
  89. if err != nil {
  90. return 0, nil, err
  91. }
  92. var questions []*learning.LearningQuestionGetRsp
  93. for _, q := range ent {
  94. content := []learning.LearningQuestionOption{}
  95. err = json.Unmarshal([]byte(q.Content), &content)
  96. if err != nil {
  97. return 0, nil, err
  98. }
  99. answer := []string{}
  100. for _, item := range content {
  101. if item.IsCorrect {
  102. answer = append(answer, item.Name)
  103. }
  104. }
  105. questions = append(questions, &learning.LearningQuestionGetRsp{
  106. LearningQuestion: *q,
  107. Answer: strings.Join(answer, " "),
  108. Content: content,
  109. })
  110. }
  111. return total, questions, err
  112. }
  113. func (s LearningQuestionService) Add(ctx context.Context, req *learning.LearningQuestionAddReq) (int, error) {
  114. validErr := gvalid.CheckStruct(ctx, req, nil)
  115. if validErr != nil {
  116. return 0, myerrors.NewMsgError(nil, validErr.Current().Error())
  117. }
  118. if req.Name == "" && req.NameImage == "" {
  119. return 0, myerrors.NewMsgError(nil, "请输入题目或题目图片")
  120. }
  121. if len(req.Content) < 2 {
  122. return 0, myerrors.NewMsgError(nil, "至少需要两个选项")
  123. }
  124. correctCount := 0
  125. for _, o := range req.Content {
  126. if o.IsCorrect {
  127. correctCount += 1
  128. }
  129. }
  130. if correctCount < 1 {
  131. return 0, myerrors.NewMsgError(nil, "正确答案未设置")
  132. }
  133. if (req.Type == 1 || req.Type == 3) && correctCount != 1 {
  134. return 0, myerrors.NewMsgError(nil, "正确答案只能设置一个")
  135. }
  136. content, err := json.Marshal(req.Content)
  137. if err != nil {
  138. return 0, err
  139. }
  140. id, err := s.Dao.InsertAndGetId(learning.LearningQuestion{
  141. SkillId: req.SkillId,
  142. Name: req.Name,
  143. NameImage: req.NameImage,
  144. Type: req.Type,
  145. Enable: req.Enable,
  146. Content: string(content),
  147. Explanation: req.Explanation,
  148. ExplanationImage: req.ExplanationImage,
  149. OperateBy: s.userInfo.RealName,
  150. CreatedAt: gtime.Now(),
  151. UpdatedAt: gtime.Now(),
  152. })
  153. if err != nil {
  154. return 0, err
  155. }
  156. return int(id), err
  157. }
  158. func (s LearningQuestionService) Update(ctx context.Context, req *learning.LearningQuestionUpdateReq) error {
  159. validErr := gvalid.CheckStruct(ctx, req, nil)
  160. if validErr != nil {
  161. return myerrors.NewMsgError(nil, validErr.Current().Error())
  162. }
  163. if len(req.Content) != 0 {
  164. if req.Type == nil {
  165. return myerrors.NewMsgError(nil, "请输入题型")
  166. }
  167. questionType := *req.Type
  168. if len(req.Content) < 2 {
  169. return myerrors.NewMsgError(nil, "至少需要两个选项")
  170. }
  171. correctCount := 0
  172. for _, o := range req.Content {
  173. if o.IsCorrect {
  174. correctCount += 1
  175. }
  176. }
  177. if correctCount < 1 {
  178. return myerrors.NewMsgError(nil, "正确答案未设置")
  179. }
  180. if (questionType == 1 || questionType == 3) && correctCount != 1 {
  181. return myerrors.NewMsgError(nil, "正确答案只能设置一个")
  182. }
  183. }
  184. q, err := s.Dao.Where("Id = ?", req.Id).One()
  185. if err != nil {
  186. return err
  187. }
  188. if q == nil {
  189. return myerrors.NewMsgError(nil, fmt.Sprintf("题目不存在: %d", req.Id))
  190. }
  191. if req.SkillId != 0 {
  192. r, err := s.Dao.DB.Table("learning_skill").Where("Id", req.SkillId).One()
  193. if err != nil {
  194. return err
  195. }
  196. if r.IsEmpty() {
  197. return myerrors.NewMsgError(nil, fmt.Sprintf("技能不存在: %d", req.SkillId))
  198. }
  199. }
  200. dao := &s.Dao.LearningQuestionDao
  201. toupdate := map[string]interface{}{}
  202. if req.SkillId != 0 {
  203. toupdate["SkillId"] = req.SkillId
  204. }
  205. if req.Name != nil {
  206. toupdate["Name"] = req.Name
  207. }
  208. if req.NameImage != nil {
  209. toupdate["NameImage"] = req.NameImage
  210. }
  211. if req.Type != nil {
  212. toupdate["Type"] = req.Type
  213. }
  214. if req.Enable != nil {
  215. toupdate["Enable"] = req.Enable
  216. }
  217. if req.Content != nil {
  218. content, err := json.Marshal(req.Content)
  219. if err != nil {
  220. return err
  221. }
  222. toupdate["Content"] = content
  223. }
  224. if req.Explanation != nil {
  225. toupdate["Explanation"] = req.Explanation
  226. }
  227. if req.ExplanationImage != nil {
  228. toupdate["ExplanationImage"] = req.ExplanationImage
  229. }
  230. if len(toupdate) == 0 {
  231. return nil
  232. }
  233. toupdate["OperateBy"] = s.userInfo.RealName
  234. _, err = dao.Where("Id", req.Id).Data(toupdate).Update()
  235. return err
  236. }
  237. func (s LearningQuestionService) Delete(ctx context.Context, id []int) error {
  238. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  239. return err
  240. }
  241. func (s LearningQuestionService) BatchUpload(ctx context.Context, req *learning.LearningQuestionBatchUploadReq) error {
  242. r, err := s.Dao.DB.Table("learning_skill").Where("Id", req.SkillId).One()
  243. if err != nil {
  244. return err
  245. }
  246. if r.IsEmpty() {
  247. return myerrors.NewMsgError(nil, fmt.Sprintf("技能不存在: %d", req.SkillId))
  248. }
  249. b, err := DownFile(req.ExcelUrl)
  250. if err != nil {
  251. return myerrors.NewMsgError(nil, fmt.Sprintf("下载 excel 异常 %s", err.Error()))
  252. }
  253. question, err := ParseQuestionExcel(req.SkillId, s.userInfo.RealName, b)
  254. if err != nil {
  255. return myerrors.NewMsgError(nil, fmt.Sprintf("解析 excel 异常 %s", err.Error()))
  256. }
  257. _, err = s.Dao.Insert(question)
  258. return err
  259. }
  260. func DownFile(url string) ([]byte, error) {
  261. r, err := http.Get(url)
  262. if err != nil {
  263. return nil, err
  264. }
  265. if r.StatusCode != http.StatusOK {
  266. return nil, fmt.Errorf("DownFile from %s StatusCode %d", url, r.StatusCode)
  267. }
  268. defer r.Body.Close()
  269. return ioutil.ReadAll(r.Body)
  270. }
  271. var allowAnswer = []string{"A", "B", "C", "D"}
  272. func ParseQuestionExcel(skillId int, operateBy string, b []byte) ([]learning.LearningQuestion, error) {
  273. f, err := excelize.OpenReader(bytes.NewBuffer(b))
  274. if err != nil {
  275. return nil, err
  276. }
  277. sheet := "Sheet1"
  278. rows, err := f.GetRows(sheet)
  279. if err != nil {
  280. return nil, err
  281. }
  282. questions := []learning.LearningQuestion{}
  283. for rown, row := range rows[1:] {
  284. rown += 1
  285. if len(row) < 9 {
  286. return nil, fmt.Errorf("excel 格式错误:列数小于9列")
  287. }
  288. name := strings.TrimSpace(row[2])
  289. typeStr := strings.TrimSpace(row[1])
  290. explanation := strings.TrimSpace(row[8])
  291. a := strings.TrimSpace(row[3])
  292. b := strings.TrimSpace(row[4])
  293. c := strings.TrimSpace(row[5])
  294. d := strings.TrimSpace(row[6])
  295. var qtype int
  296. switch typeStr {
  297. case "单选题":
  298. qtype = 1
  299. case "多选题":
  300. qtype = 2
  301. case "判断题":
  302. qtype = 3
  303. default:
  304. return nil, fmt.Errorf("excel 格式错误:不合法的题型 '%s' %d", typeStr, rown)
  305. }
  306. answerStr := strings.TrimSpace(row[7])
  307. answer := strings.Split(answerStr, " ")
  308. for i := range answer {
  309. pass := false
  310. for _, allow := range allowAnswer {
  311. if answer[i] == allow {
  312. pass = true
  313. break
  314. }
  315. }
  316. if !pass {
  317. return nil, fmt.Errorf("excel 格式错误:不合法的答案:'%s' %d", answer[i], rown)
  318. }
  319. }
  320. options := []learning.LearningQuestionOption{
  321. {
  322. Name: "A",
  323. Content: a,
  324. IsCorrect: strings.Contains(answerStr, "A"),
  325. },
  326. {
  327. Name: "B",
  328. Content: b,
  329. IsCorrect: strings.Contains(answerStr, "B"),
  330. },
  331. {
  332. Name: "C",
  333. Content: c,
  334. IsCorrect: strings.Contains(answerStr, "C"),
  335. },
  336. {
  337. Name: "D",
  338. Content: d,
  339. IsCorrect: strings.Contains(answerStr, "D"),
  340. },
  341. }
  342. correctCount := 0
  343. for _, o := range options {
  344. if o.IsCorrect {
  345. correctCount += 1
  346. }
  347. }
  348. if correctCount < 1 {
  349. return nil, fmt.Errorf("excel 格式错误:含有未设置正确答案的题目 %d", rown)
  350. }
  351. if (qtype == 1 || qtype == 3) && correctCount != 1 {
  352. return nil, fmt.Errorf("excel 格式错误:含有设置正确答案和题型不符的题目 %d", rown)
  353. }
  354. content, _ := json.Marshal(options)
  355. q := learning.LearningQuestion{
  356. SkillId: skillId,
  357. Name: name,
  358. Type: qtype,
  359. Enable: 1,
  360. Content: string(content),
  361. Explanation: explanation,
  362. OperateBy: operateBy,
  363. CreatedAt: gtime.New(),
  364. UpdatedAt: gtime.New(),
  365. }
  366. questions = append(questions, q)
  367. }
  368. return questions, nil
  369. }
  370. func QuestionTemplate() (*excelize.File, error) {
  371. f := excelize.NewFile()
  372. sheet := "Sheet1"
  373. header := []string{
  374. "序号", "题型", "题目", "选项A", "选项B", "选项C", "选项D", "正确答案", "解析",
  375. }
  376. colWidth := []float64{
  377. 12, 12, 40, 20, 20, 20, 20, 12, 20,
  378. }
  379. tempData := [][]string{
  380. {"1", "单选题", "凝胶成像系统不能对以下哪些进行图像采集分析?", "蛋白凝胶", "培养皿", "DNA凝胶", "96孔细胞板", "B", "无"},
  381. {"2", "多选题", "凝胶成像系统有哪几种紫外光源可以选择?", "254mm为中心的宽波长紫外光源", "302mm为中心的宽波长紫外光源", "365mm为中心的宽波长紫外光源", "380mm为中心的宽波长紫外光源", "A B C", "无"},
  382. {"3", "判断题", "凝胶成像系统对紫外线光源有保护功能,如暗室门未关紧,系统将自动切断紫外,是否正确?", "正确", "错误", "", "", "A", "无"},
  383. }
  384. colStyle, err := f.NewStyle(&excelize.Style{
  385. Alignment: &excelize.Alignment{
  386. Horizontal: "center",
  387. Vertical: "center",
  388. WrapText: true,
  389. },
  390. Font: &excelize.Font{
  391. Size: 11,
  392. Family: "宋体",
  393. },
  394. })
  395. if err != nil {
  396. return nil, err
  397. }
  398. headerStyle, err := f.NewStyle(&excelize.Style{
  399. Alignment: &excelize.Alignment{
  400. Horizontal: "center",
  401. },
  402. Fill: excelize.Fill{
  403. Type: "pattern",
  404. Color: []string{"#a6a6a6"},
  405. Pattern: 1,
  406. },
  407. Border: []excelize.Border{
  408. {Type: "left", Color: "#000000", Style: 1},
  409. {Type: "top", Color: "#000000", Style: 1},
  410. {Type: "bottom", Color: "#000000", Style: 1},
  411. {Type: "right", Color: "#000000", Style: 1},
  412. },
  413. })
  414. if err != nil {
  415. return nil, err
  416. }
  417. err = f.SetColStyle(sheet, "A:I", colStyle)
  418. if err != nil {
  419. return nil, err
  420. }
  421. err = f.SetCellStyle(sheet, "A1", "I1", headerStyle)
  422. if err != nil {
  423. return nil, err
  424. }
  425. for i := range header {
  426. n, err := excelize.ColumnNumberToName(i + 1)
  427. if err != nil {
  428. return nil, err
  429. }
  430. f.SetCellValue(sheet, n+"1", header[i])
  431. }
  432. for i, w := range colWidth {
  433. n, err := excelize.ColumnNumberToName(i + 1)
  434. if err != nil {
  435. return nil, err
  436. }
  437. err = f.SetColWidth(sheet, n, n, w)
  438. if err != nil {
  439. return nil, err
  440. }
  441. }
  442. for row, item := range tempData {
  443. for col, v := range item {
  444. colName, err := excelize.ColumnNumberToName(col + 1)
  445. if err != nil {
  446. return nil, err
  447. }
  448. rowName := strconv.Itoa(row + 2)
  449. f.SetCellValue(sheet, colName+rowName, v)
  450. }
  451. }
  452. index := f.NewSheet(sheet)
  453. f.SetActiveSheet(index)
  454. return f, nil
  455. }