question.go 14 KB

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