<template>
  <div
    class="ws-main"
    :style="[{'padding-bottom':'120px'}]"
  >
    <!-- <WsBackLabel
      v-if="backRoute"
      @click="$router.go(-1)"
      :label="backRouteText"
    /> -->
    <WsTitle>批次上傳{{label}}</WsTitle>
    <v-stepper
      v-model="step"
      class="elevation-0 transparent"
    >
      <v-stepper-header class="elevation-0">
        <v-stepper-step
          step="1"
          editable
        >
          選擇分段依據
        </v-stepper-step>

        <v-divider></v-divider>
        <v-stepper-step
          step="2"
          editable
        >
          匯入來源
        </v-stepper-step>

        <v-divider></v-divider>

        <v-stepper-step
          step="3"
          editable
        >編輯內容</v-stepper-step>
      </v-stepper-header>
      <v-stepper-items class="mt-5">
        <v-stepper-content
          step="1"
          class="pa-0"
        >
          <WsCard>
            <div
              class="ws-content"
              :style="{'min-height':'300px'}"
            >
              <v-row>
                <v-col
                  cols="12"
                  sm="3"
                >
                  <WsState
                    v-if="dividePreTitle"
                    :label="dividePreTitle.label"
                    :type="dividePreTitle.type"
                    v-model="dividePreTitleValue"
                    :items="dividePreTitle.items"
                  ></WsState>
                </v-col>
                <v-col
                  cols="12"
                  sm="3"
                >
                  <WsState
                    v-if="divideTitle"
                    :label="divideTitle.label"
                    :type="divideTitle.type"
                    v-model="divideTitleValue"
                    :items="divideTitle.items"
                  ></WsState>
                </v-col>
              </v-row>
              <v-row v-if="localeMode">
                <v-col
                  cols="12"
                  sm="3"
                >
                  <WsState
                    label="輸入語言"
                    type="select"
                    v-model="locale"
                    :items="_localeItems"
                  ></WsState>
                </v-col>
              </v-row>
            </div>
          </WsCard>
        </v-stepper-content>

        <v-stepper-content
          step="2"
          class="pa-0"
        >
          <v-row>
            <v-col>
              <WsCard>
                <div
                  class="ws-content"
                  :style="{'min-height':'300px'}"
                >
                  <WsContentTitle>{{compareTitleFirst}}</WsContentTitle>
                  <WsState
                    :label="`${compareTitleFirst}原文`"
                    type="textarea"
                    v-model="contentFirst"
                  ></WsState>
                </div>
              </WsCard>
            </v-col>
            <v-col>
              <WsCard>
                <WsContent minHeight="300px">
                  <WsContentTitle>{{compareTitleSecond}}</WsContentTitle>
                  <WsState
                    :label="`${compareTitleSecond}原文`"
                    type="textarea"
                    v-model="contentSecond"
                  ></WsState>
                </WsContent>
              </WsCard>
            </v-col>
          </v-row>
        </v-stepper-content>

        <v-stepper-content step="3">
          <WsCompareMerge
            :titleFirst="compareTitleFirst"
            :titleSecond="compareTitleSecond"
            :firstData="firstParseResult"
            :secondData="secondParseResult"
            :inputFields="_compareFields"
            compareField="content"
          ></WsCompareMerge>
        </v-stepper-content>
      </v-stepper-items>
    </v-stepper>
    <WsMainBottomNav>
      <WsBtn
        v-if="step>1"
        @click="$_onPrevClick()"
        color="textSecondary"
        outlined
      >上一步</WsBtn>
      <WsBtn
        v-if="step<3"
        :loading="submitLoading"
        @click="$_onNextClick()"
      >下一步</WsBtn>
      <WsBtn
        v-if="step==3"
        @click="$_onSubmit()"
        :loading="submitLoading"
      >送出</WsBtn>
    </WsMainBottomNav>
  </div>
</template>

<script>
export default {
  data: () => ({
    step: 1,
    submitLoading: false,
    contentFirst: "",
    contentSecond: "",
    divideTitleValue: null,
    dividePreTitleValue: null,
    locale: null,
    firstParseResult: [],
    secondParseResult: [],
  }),
  computed: {
    _localeItems() {
      const _localeItems = [];
      const locales = this.$store.state.locale.locales;
      if (!locales) {
        return null;
      }
      locales.forEach((locale) => {
        _localeItems.push({
          value: locale.code,
          text: locale.name,
        });
      });
      return _localeItems;
    },
    _compareFields() {
      return {
        preTitle: {
          type: "text",
          label: this.preTitleLabel,
        },
        title: {
          type: "text",
          label: this.titleLabel,
        },
        content: {
          type: "textarea",
          label: this.contentLabel,
          withCompareTitle: true,
        },
      };
    },
    _parseContentFirst() {
      if (!this.contentFirst) {
        return null;
      } else {
        return this.$_getParseArr(this.contentFirst);
      }
    },
    _parseContentSecond() {
      if (!this.contentSecond) {
        return null;
      } else {
        return this.$_getParseArr(this.contentSecond);
      }
    },
  },
  methods: {
    loadingStart() {
      this.submitLoading = true;
    },
    loadingStop() {
      this.submitLoading = false;
    },
    $_getParseArr(text) {
      const parseArr = [];
      const lineArr = text.match(/[^\r\n]+/g);
      // const lineArr = text.match(
      //   /(<h1>.*?<\/h1>|<h2>.*?<\/h2>|<h3>.*?<\/h3>|<h4>.*?<\/h4>|<h5>.*?<\/h5>|<h6>.*?<\/h6>|<p>.*?<\/p>|<table>.*?<\/table>|<div>.*?<\/div>|<b>.*?<\/b>|<strong>.*?<\/strong>)/g
      // );
      lineArr.forEach((lineArrItem) => {
        // 前後空格移除
        const line = lineArrItem.trim();
        if (this.dividePreTitleValue) {
          const preTitleMatchArr = line.match(this.dividePreTitleValue);
          if (preTitleMatchArr) {
            parseArr.push({
              preTitle: `${preTitleMatchArr[1].trim()} ${preTitleMatchArr[2].trim()}`,
              title: "",
              content: "",
            });
          } else {
            const titleMatchArr = line.match(this.divideTitleValue);
            const lastParse = parseArr[parseArr.length - 1];
            if (titleMatchArr) {
              if (lastParse && !lastParse.title) {
                lastParse.title = titleMatchArr[1].trim();
                lastParse.content = titleMatchArr[2].trim();
              } else {
                parseArr.push({
                  title: titleMatchArr[1].trim(),
                  content: titleMatchArr[2].trim(),
                });
              }
            } else {
              if (lastParse) {
                lastParse.content += lineArrItem;
              }
            }
          }
        } else {
          const titleMatchArr = line.match(this.divideTitleValue);
          if (titleMatchArr) {
            parseArr.push({
              title: titleMatchArr[1].trim(),
              content: titleMatchArr[2].trim(),
            });
          } else {
            const lastParse = parseArr[parseArr.length - 1];
            if (lastParse) {
              lastParse.content += lineArrItem;
            }
          }
        }
      });
      return parseArr;
    },
    $_getSBC(str) {
      let result = "";
      for (var i = 0; i < str.length; i++) {
        var cCode = str.charCodeAt(i);
        //全形與半形相差（除空格外）：65248（十進位制）
        cCode = cCode >= 0xff01 && cCode <= 0xff5e ? cCode - 65248 : cCode;
        //處理空格
        cCode = cCode == 0x03000 ? 0x0020 : cCode;
        result += String.fromCharCode(cCode);
      }
      return result;
    },
    $_getDBC(str) {
      var result = "";
      for (var i = 0; i < str.length; i++) {
        var cCode = str.charCodeAt(i);
        //全形與半形相差（除空格外）：65248(十進位制)
        cCode = cCode >= 0x0021 && cCode <= 0x007e ? cCode + 65248 : cCode;
        //處理空格
        cCode = cCode == 0x0020 ? 0x03000 : cCode;
        result = String.fromCharCode(cCode);
      }
      return result;
    },
    $_onPrevClick() {
      this.step--;
    },
    $_onNextClick() {
      this.step++;
    },
    $_submitCheck() {
      let check = true;
      for (let i = 0; i < this.firstParseResult.length; i++) {
        if (this.firstParseResult[i] && this.secondParseResult[i]) {
          check = false;
        }
      }
      return check;
    },
    $_onSubmit() {
      if (!this.$_submitCheck()) {
        alert("比較未完成");
        return;
      }
      if (!this.locale) {
        alert("請選擇語言");
        this.step = 1;
        return;
      }
      const submitArr = [];
      for (let i = 0; i < this.firstParseResult.length; i++) {
        if (this.firstParseResult[i]) {
          submitArr.push(this.firstParseResult[i]);
        } else if (this.secondParseResult[i]) {
          submitArr.push(this.secondParseResult[i]);
        }
      }
      const submitData = {
        submitArr: submitArr,
      };
      if (this.localeMode) {
        submitData.locale = this.locale;
      }
      this.$emit("submit", submitData);
    },
  },
  watch: {
    step: {
      handler() {
        if (this.step == "3") {
          this.submitLoading = true;
          setTimeout(() => {
            this.firstParseResult = this._parseContentFirst;
            this.secondParseResult = this._parseContentSecond;
            this.submitLoading = false;
          }, 500);
        }
      },
    },
    // _parseContentFirst: {
    //   handler() {
    //     this.firstParseResult = this._parseContentFirst;
    //   }
    // },
    // _parseContentSecond: {
    //   handler() {
    //     this.secondParseResult = this._parseContentSecond;
    //   }
    // }
  },
  props: {
    localeMode: {
      type: Boolean,
      default: false,
    },
    dividePreTitle: {
      type: Object,
      default: null,
    },
    divideTitle: {
      type: Object,
      default: null,
    },
    label: {
      type: String,
      default: null,
    },
    backRoute: {
      type: String,
      default: null,
    },
    backRouteText: {
      type: String,
      default: "返回",
    },
    modelName: {
      type: String,
      default: null,
    },
    compareMode: {
      type: Boolean,
      default: false,
    },
    compareTitleFirst: {
      type: String,
      default: null,
    },
    compareTitleSecond: {
      type: String,
      default: null,
    },
  },
};
</script>

<style>
</style>