text: import React, { useState } from "react";
  import { Link } from "react-router-dom";
  import store from "data/store"
  import axios from "axios";
  import { useCookies } from 'react-cookie';
  import { useForm } from "react-hook-form";
  import option from "data/option.js"
  import { Checkbox, CheckboxGroup, SelectPicker, Toggle, Icon, Loader, Uploader, InputNumber, InputGroup } from 'rsuite';
  //date
  import 'assets/styles/daterange.css';
  import { DateRange } from 'react-date-range';
  import { addDays } from 'date-fns';
  import 'react-date-range/dist/styles.css';
  import 'react-date-range/dist/theme/default.css';
  //editor
  import { convertToRaw } from 'draft-js';
  import { Editor } from 'react-draft-wysiwyg';
  import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
  import draftToHtml from 'draftjs-to-html';
  import moment from "moment";
  import Resizer from "react-image-file-resizer";
  import QuillEditor from '../../../../components/Editor/QuillEditor.js';
  
  const resizeFile = (file) => {
      let filetype = file.type == 'image/png' ? "PNG" : "JPEG";
      return new Promise((resolve) => {
          Resizer.imageFileResizer(
              file,
              1000,
              1000,
              filetype,
              100,
              0,
              (uri) => {
                  resolve(uri);
              },
              "blob"
          );
      });
  }
  function previewFile(file, callback) {
      const reader = new FileReader();
      reader.onloadend = () => {
          callback(reader.result);
      };
      reader.readAsDataURL(file);
  }
  const styles = {
      width: 150,
      height: 150
  };
  async function getArrayBuffer(file) {
      let image = await resizeFile(file);
  
      return new Promise((resolve, reject) => {
          // STEP 3: 轉成 ArrayBuffer, i.e., reader.result
          const reader = new FileReader();
          reader.addEventListener('load', () => {
              resolve(Array.from(new Uint8Array(reader.result)));
          });
          reader.readAsArrayBuffer(image);
      })
  }
  
  export default function CardUserSettings(props) {
      const { register, control, formState: { errors }, handleSubmit, setValue } = useForm();
      const [cookies, setCookie] = useCookies();
      const [submit, setSubmit] = React.useState(false);
      const [uploading, setUploading] = React.useState(false);
      const [fileInfo, setFileInfo] = React.useState(null);
      const [courseUpload, setcourseUpload] = useState(0);
      const [orderType, setOrderType] = useState(0);
      const [fixed, setFixed] = useState(0);
      setValue("fixed", 0);
      const [studentLimit, setstudentLimit] = useState(1);
      const [minus_bool, setminus_bool] = useState(true);
      const [makeup, setmakeup] = useState(0);
      const [vacation, setvacation] = useState(0);
      const [payType, setpayType] = useState();
      const [courseType, setcourseType] = useState();
      const [storeId, setstoreId] = useState();
      const [courseEditor, setcourseEditor] = useState();
      const [courseDays, setCourseDays] = React.useState([]);
      const [uploadedImages, setuploadedImages] = React.useState([]);
      const [editValue, setEditValue] = useState('');
      const [fileName, setFileName] = useState();
  
      const fromQuill = (data) => {
          setEditValue(data);
          setValue("courseEditor", data);
      }
  
      const typeChange = (option) => {
          setValue('typeId', option)
      }
  
      const [date, setDate] = useState({
          selection: {
              startDate: null,
              endDate: null,
              key: 'selection'
          },
      });
  
      const _uploadImageCallBack = (file) => {
          const imageObject = {
              file: file,
              localSrc: URL.createObjectURL(file),
          }
          let image = []
          image.push(imageObject);
          setuploadedImages(image)
  
          return new Promise(
              (resolve, reject) => {
                  resolve({ data: { link: imageObject.localSrc } });
              }
          );
      }
      const handleMinus = () => {
          if (studentLimit == 0)
              return
          if (studentLimit == 1)
              setminus_bool(true)
          setValue('studentLimit', studentLimit + 1)
          setstudentLimit(studentLimit - 1);
      };
      const handlePlus = () => {
          if (studentLimit == 0)
              setminus_bool(false)
          setValue('studentLimit', studentLimit + 1)
  
          setstudentLimit(studentLimit + 1);
      };
      const handleLimit = (v) => {
          setstudentLimit(v);
          setValue('studentLimit', v)
      };
      const Change_courseUpload = (e) => {
          setcourseUpload(e)
          setValue("courseUpload", e)
      };
      const Change_orderType = (e) => {
          setOrderType(e)
          setValue("orderType", e)
      };
      const changeFixed = (e) => {
          let value = e ? 1 : 0;
          setFixed(value);
          setValue("fixed", value);
      }
      const Change_makeup = (e) => {
          setmakeup(e)
          setValue("makeup", e)
      };
      const Change_vacation = (e) => {
          setvacation(e)
          setValue("vacation", e)
      };
      const courseTypeChange = (option) => {
          setcourseType(option)
      }
      const storeIdChange = (option) => {
          setstoreId(option)
      }
      const onEditorStateChange = (editorState) => {
          var data = draftToHtml(convertToRaw(editorState.getCurrentContent()))
          setcourseEditor(editorState)
          setValue("courseEditor", data)
      }
      const onSubmit = jsonData => {
          setSubmit(true)
          let tempDays = ['0', '0', '0', '0', '0', '0', '0'];
          jsonData.courseDays.forEach(day => {
              tempDays[parseInt(day) - 1] = "1";
          });
          jsonData.courseDays = tempDays.join("");
  
          jsonData["type"] = jsonData["typeId"] && jsonData["typeId"].value
          if (jsonData.courseImg) {
              jsonData["imageName"] = fileName;
          }
  
          const headers = {
              'Authorization': 'Bearer ' + cookies.token,
              "Content-Type": "application/json"
          };
          axios.post(store.webApiUrl + 'Course/Create', jsonData, { headers })
              .then(r => {
                  if (r.status == "200") {
                      alert("新增成功")
                      window.location.reload(false);
                  } else {
                      alert("新增失敗")
                  }
                  setSubmit(false)
              });
      }
      return (
          <>
              <div className="relative flex flex-col min-w-0 break-words w-full mb-6 shadow-lg rounded-lg bg-blueGray-100 border-0">
                  <form onSubmit={handleSubmit(onSubmit)}>
                      <div className="rounded-t bg-white mb-0 px-6 py-6">
                          <div className="relative w-full px-4 max-w-full flex flex-1 justify-between">
                              <div className="flex flex-wrap">
                                  <h6 className="text-blueGray-700 text-xl font-bold ">課程資料(新增)</h6>
                                  <Link to="/admin/course" onClick={() => window.location.reload()} className="pl-4">
                                      <button
                                          className="bg-emerald-500 text-white active:bg-lightBlue-600 font-bold uppercase text-xs p-4 px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"
                                          type="button"
                                      >
                                          返回
                                      </button>
                                  </Link>
                              </div>
                              <div className="flex flex-wrap">
                                  <div>
                                      <div className="pr-4">
                                          <Toggle size="lg"
                                              checked={orderType}
                                              onChange={Change_orderType}
                                              checkedChildren="團體課程"
                                              unCheckedChildren="私人課程"
                                          />
                                      </div>
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("orderType", { required: false })}
                                      />
                                  </div>
                                  <div>
                                      <div className="pr-4">
                                          <Toggle size="lg"
                                              checked={courseUpload}
                                              onChange={Change_courseUpload}
                                              checkedChildren="上架中"
                                              unCheckedChildren="未上架"
                                          />
                                      </div>
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("courseUpload", { required: false })}
                                      />
                                  </div>
                                  <button
                                      className={((submit) ? "bg-lightBlue-200 " : "bg-lightBlue-500 ") + "text-white active:bg-lightBlue-600 font-bold uppercase text-xs px-4 py-2 rounded shadow hover:shadow-md outline-none focus:outline-none mr-1 ease-linear transition-all duration-150"}
                                      type="submit"
                                  // disabled={submit}
                                  >
                                      新增
                                  </button>
                              </div>
                          </div>
                      </div>
                      <div className="flex-auto px-4 lg:px-10 py-10 pt-0">
                          <h6 className="text-blueGray-400 text-sm mt-3 mb-6 font-bold uppercase">
                              課程設定
                          </h6>
                          <div className="flex flex-wrap">
                              <div className="w-full lg:w-6/12 px-4">
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              分類
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <SelectPicker appearance="default" onChange={courseTypeChange}
                                          placeholder="選擇課程類型" data={option.courseType} block />
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("courseType", { value: courseType, required: true })}
                                      />
                                      {errors.courseType && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              選擇門市
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <SelectPicker defaultValue={null} appearance="default" onChange={storeIdChange}
                                          placeholder="選擇門市" data={option.branch_list} block />
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("storeId", { value: storeId, required: true })}
                                      />
                                      {errors.storeId && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                  </div>
                              </div>
                              <div className="w-full lg:w-3/12 px-4">
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              上傳課程圖片
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <Uploader
                                          fileListVisible={false}
                                          listType="picture"
                                          // action={null}
                                          onUpload={file => {
                                              setUploading(true);
                                              setFileName(file.name);
                                              previewFile(file.blobFile, value => {
                                                  setFileInfo(value);
                                                  setUploading(false);
                                                  getArrayBuffer(file.blobFile).then((r) => {
                                                      setValue("courseImg", r)
                                                  })
                                              });
                                          }}
                                      >
                                          <button style={styles} type="button">
                                              {uploading && <Loader backdrop center />}
                                              {fileInfo ? (
                                                  <img src={fileInfo} width="100%" height="100%" max-height="150px" />
                                              ) : (
                                                  <Icon icon="camera" size="5x" />
                                              )}
                                          </button>
                                      </Uploader>
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("courseImg", { required: true })}
                                      />
                                      {errors.courseImg && <div style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</div>}
                                  </div>
                              </div>
                              <div className="w-full lg:w-3/12 px-4">
                                  <div className="relative w-full mb-3">
                                      <label
                                          className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
                                          htmlFor="grid-password"
                                      >
                                          開放補課
                                      </label>
                                      <div className="pr-4">
                                          <Toggle size="lg"
                                              checked={makeup}
                                              onChange={Change_makeup}
                                              checkedChildren="Open"
                                              unCheckedChildren="Close"
                                          />
                                      </div>
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("makeup", { required: false })}
                                      />
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <label
                                          className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
                                          htmlFor="grid-password"
                                      >
                                          開放請假
                                      </label>
                                      <div className="pr-4">
                                          <Toggle size="lg"
                                              checked={vacation}
                                              onChange={Change_vacation}
                                              checkedChildren="Open"
                                              unCheckedChildren="Close"
                                          />
                                      </div>
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("vacation", { required: false })}
                                      />
                                  </div>
                              </div>
                          </div>
                          <h6 className="text-blueGray-400 text-sm mt-3 mb-6 font-bold uppercase">
                              課程資料
                          </h6>
                          <div className="flex flex-wrap">
                              <div className="w-full lg:w-6/12 px-4">
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              課程名稱
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <input
                                          type="text"
                                          className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
                                          {...register("courseName", { required: true })}
                                      />
                                      {errors.courseName && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              課程編號
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <input
                                          type="text"
                                          className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
                                          {...register("courseSerial", { required: true, pattern: /^[A-Za-z\d\u4E00-\u9FA5]*$/ })}
                                      />
                                      {errors.courseSerial?.type === 'required' && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                      {errors.courseSerial?.type === 'pattern' && <span style={{ color: "red", fontSize: "0.8rem" }}>Field can only contain numbers, English characters, and Chinese characters.</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              人數限制
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <InputGroup>
                                          <InputGroup.Button onClick={handleMinus} disabled={minus_bool} >-</InputGroup.Button>
                                          <InputNumber
                                              size="lg"
                                              className={'custom-input-number'}
                                              min='1'
                                              value={studentLimit}
                                              onChange={handleLimit}
                                          />
                                          <InputGroup.Button onClick={handlePlus}>+</InputGroup.Button>
                                      </InputGroup>
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              課程總數(單位:節/堂)
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <input
                                          type="text"
                                          className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
                                          {...register("courseNum", { required: true, pattern: /^[\d]*$/ })}
                                      />
                                      {errors.courseNum?.type === 'required' && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                      {errors.courseNum?.type === 'pattern' && <span style={{ color: "red", fontSize: "0.8rem" }}>Field can only contain numbers.</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              課程時數 (分鐘)
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <input
                                          type="text"
                                          className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
                                          {...register("courseLength", { required: true, pattern: /^[\d]*$/ })}
                                      />
                                      {errors.courseLength?.type === 'required' && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                      {errors.courseLength?.type === 'pattern' && <span style={{ color: "red", fontSize: "0.8rem" }}>Field can only contain numbers.</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              原價
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <input
                                          type="text"
                                          className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
                                          {...register("price", { required: true, pattern: /^[\d]*$/ })}
                                      />
                                      {errors.price?.type === 'required' && <span style={{ color: "red", fontSize: "0.8rem" }}>This field is required.</span>}
                                      {errors.price?.type === 'pattern' && <span style={{ color: "red", fontSize: "0.8rem" }}>Field can only contain numbers.</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <label
                                          className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
                                          htmlFor="grid-password"
                                      >
                                          特價
                                      </label>
                                      <input
                                          type="text"
                                          className="border-0 px-3 py-3 placeholder-blueGray-300 text-blueGray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"
                                          {...register("discount", { required: false, pattern: /^[\d]*$/ })}
                                      />
                                      {errors.discount?.type === 'pattern' && <span style={{ color: "red", fontSize: "0.8rem" }}>Field can only contain numbers.</span>}
                                  </div>
                              </div>
                              <div className="w-full lg:w-6/12 px-4">
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              課程週期
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <CheckboxGroup
                                          inline
                                          name="checkboxList"
                                          value={courseDays}
                                          onChange={setCourseDays}
                                      >
                                          <Checkbox value="1">一</Checkbox>
                                          <Checkbox value="2">二</Checkbox>
                                          <Checkbox value="3">三</Checkbox>
                                          <Checkbox value="4">四</Checkbox>
                                          <Checkbox value="5">五</Checkbox>
                                          <Checkbox value="6">六</Checkbox>
                                          <Checkbox value="7">日</Checkbox>
                                      </CheckboxGroup>
                                      <input
                                          type="text"
                                          hidden={true}
                                          {...register("courseDays", { value: courseDays, required: true })}
                                      />
                                      {errors.courseDays && <span style={{ color: "red", fontSize: "0.8rem" }}>請選擇週期</span>}
                                  </div>
                                  <div className="relative w-full mb-3">
                                      <div className="flex item-center mb-2">
                                          <label
                                              className="block uppercase text-blueGray-600 text-xs font-bold"
                                              htmlFor="grid-password"
                                          >
                                              上課時間
                                          </label>
                                          <div className="text-red-500 text-xs font-bold ml-1">*</div>
                                      </div>
                                      <DateRange
                                          editableDateInputs={true}
                                          onChange={item => setDate({ ...date, ...item })}
                                          months={1}
                                          minDate={addDays(new Date(), -300)}
                                          maxDate={addDays(new Date(), 900)}
                                          // onChange={dateChange}
                                          className=""
                                          direction="horizontal"
                                          scroll={{ enabled: true }}
                                          ranges={[date.selection]}
                                          dateDisplayFormat="yyyy/M/dd"
                                      />
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("courseStartDate", { value: date.selection.startDate, required: true })}
                                      />
                                      {errors.courseStartDate && <div style={{ color: "red", fontSize: "0.8rem" }}>請選擇開始時間</div>}
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("courseEndDate", { value: date.selection.endDate, required: true })}
                                      />
                                      {errors.courseEndDate && <div style={{ color: "red", fontSize: "0.8rem" }}>請選擇結束時間</div>}
                                  </div>
                              </div>
                          </div>
                          <hr className="mt-6 border-b-1 border-blueGray-300" />
                          <h6 className="text-blueGray-400 text-sm mt-3 mb-6 font-bold uppercase">
                              關於
                          </h6>
                          <div className="flex flex-wrap">
                              <div className="w-full lg:w-12/12 px-4">
                                  <div className="relative w-full mb-3">
                                      <label
                                          className="block uppercase text-blueGray-600 text-xs font-bold mb-2"
                                          htmlFor="grid-password"
                                      >
                                          其他內容
                                      </label>
                                      <div className="h-96 overflow-y-auto overflow-x-auto">
                                          <QuillEditor
                                              value={editValue}
                                              toParent={fromQuill}
                                          />
                                          {/* <Editor
                                              editorState={courseEditor}
                                              wrapperClassName="demo-wrapper"
                                              editorClassName="demo-editor"
                                              onEditorStateChange={onEditorStateChange}
                                              toolbar={{
                                                  options: ['inline', 'blockType', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'emoji', 'remove'],
                                                  image: {
                                                      uploadCallback: _uploadImageCallBack,
                                                      previewImage: true,
                                                      alt: { present: true, mandatory: false },
                                                      inputAccept: 'image/gif,image/jpeg,image/jpg,image/png,image/svg',
                                                      defaultSize: {
                                                          height: '150px',
                                                          width: '150px',
                                                      },
                                                  },
                                              }}
                                          /> */}
                                      </div>
                                      <input
                                          style={{ opacity: 0, position: "absolute" }}
                                          {...register("courseEditor", { required: false })}
                                      />
                                  </div>
                              </div>
                          </div>
                      </div>
                  </form>
              </div>
          </>
      );
  }