<!-- TODO push文案库 使用 消息文案库代替 暂无其他地方使用后面可直接删除-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.pushType"
        placeholder="推送类型"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option value="STRATEGY" label="策略" />
      </el-select>

      <el-select
        v-model="listQuery.pushBusinessScene"
        placeholder="业务场景"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in messageBusinessScene"
          :key="item.value"
          :value="item.value"
          :label="item.name"
        />
      </el-select>

      <!-- <el-select
        v-model="listQuery.pushUserType"
        placeholder="用户类型"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in userTypes"
          :key="item.value"
          :value="item.value"
          :label="item.name"
        />
      </el-select> -->
      <div class="filter-item">
        <el-date-picker
          v-model="rangeCreateDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="创建时间"
          end-placeholder="创建时间"
        />
      </div>
      <div class="filter-item">
        <el-date-picker
          v-model="latestRangeDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="最近发送时间"
          end-placeholder="最近发送时间"
        />
      </div>

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-refresh"
        @click="handleSynchronize"
      >
        一键同步翻译
      </el-button>
      <el-tooltip class="item" effect="dark">
        <div slot="content">
          <p>
            如果后台有更新语言，请先同步翻译现有模板消息，然后再进行新增/修改
          </p>
        </div>
        <i class="el-icon-question" style="font-size:26px;" />
      </el-tooltip>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="pushTypeName" label="推送类型" align="center" />
      <el-table-column
        prop="businessSceneName"
        label="业务场景"
        align="center"
      />
      <!-- <el-table-column prop="pushUserTypeName" label="用户类型" align="center" /> -->
      <el-table-column prop="sysPushTextContents" label="标题" align="center">
        <template slot-scope="scope">
          <span
            v-if="
              !scope.row.sysPushTextContents ||
                scope.row.sysPushTextContents.length === 0
            "
          >暂无标题</span>
          <span v-else>{{ scope.row.sysPushTextContents[0].title }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="sysPushTextContents"
        label="文案内容"
        align="center"
      >
        <template slot-scope="scope">
          <span
            v-if="
              !scope.row.sysPushTextContents ||
                scope.row.sysPushTextContents.length === 0
            "
          >暂无文案</span>
          <span v-else>{{ scope.row.sysPushTextContents[0].content }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="latestTime" label="最近发送时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.latestTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.user">{{ scope.row.user.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click.native="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="text"
            @click.native="handlePushTextHistory(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />
    <el-dialog
      title="已录入语言"
      :visible="pushTextHistoryVisible"
      :before-close="handlerPushTextHistoryClose"
      width="70%"
    >
      <div
        v-loading="pushTextHistoryLoading"
        style="max-height:500px;overflow:auto"
      >
        <el-card
          v-for="item in pushTextHistory"
          :key="item.id"
          style="margin-bottom: 10px"
        >
          <h4>{{ item.languageName }}</h4>
          <p>标题：{{ item.title }}</p>
          <p>内容：{{ item.content }}</p>
        </el-card>
      </div>
    </el-dialog>
    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handlerFormClose"
      width="400px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="推送类型" prop="pushType">
            <el-select
              v-model="form.pushType"
              disabled
              placeholder="推送类型"
              class="filter-item"
            >
              <el-option value="STRATEGY" label="策略" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务场景" prop="businessScene">
            <el-select
              v-model="form.businessScene"
              placeholder="业务场景"
              class="filter-item"
            >
              <el-option
                v-for="item in messageBusinessScene"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="用户类型" prop="pushUserType">
            <el-select
              disabled
              v-model="form.pushUserType"
              placeholder="用户类型"
              class="filter-item"
            >
              <el-option
                v-for="item in userTypes"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="语言类型" prop="language">
            <el-select
              ref="language"
              v-model="form.language"
              placeholder="语言类型"
              class="filter-item"
              @change="handleLanguageChange"
            >
              <el-option
                v-for="item in language"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select>
          </el-form-item>-->
          <!--<div style="padding: 0px 0px 20px 15px;"> 共计 <span class="font-danger">{{ language.length }}</span> 语言<span v-if="languageNames && languageNames.length > 0">、已录入：{{ languageNames.join(',') }}</span></div>
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="form.title" type="text" @blur="handleLanguageBlur" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model.trim="form.content" type="textarea" @blur="handleLanguageBlur" />
          </el-form-item>-->
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="form.title" type="text" />
          </el-form-item>
          <el-form-item label="模板内容" prop="content">
            <el-input
              v-model.trim="form.content"
              placeholder="请输入模板，尽量简洁明了..."
              type="textarea"
              :rows="4"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">保存</el-button>
            <el-button @click="resetForm()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userTypes, messageBusinessScene, language } from '@/constant/type'
import {
  pushTextStoreTable,
  addPushTextStore,
  updatePushTextStore,
  getPushTextHistory,
  synchronPushText
} from '@/api/message'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  data() {
    return {
      rangeCreateDate: '',
      latestRangeDate: '',
      messageBusinessScene,
      userTypes,
      language,
      pushTextHistoryLoading: false,
      pushTextHistoryVisible: false,
      pushTextHistory: [],
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        pushType: '',
        pushBusinessScene: '',
        pushUserType: '',
        startTime: '',
        endTime: '',
        startLastDate: '',
        endLastDate: ''
      },
      formVisible: false,
      textOptTitle: '添加推送文案',
      form: {
        id: '',
        pushType: 'STRATEGY',
        businessScene: 'CARD_LIKE',
        pushUserType: 'ALL',
        title: '',
        content: ''
      },
      submitLoading: false,
      languageMap: {},
      languageNames: [],
      prevSelectedVal: 'en',
      rules: {
        pushType: [
          { required: true, message: '请选择推送类型', trigger: 'blur' }
        ],
        businessScene: [
          { required: true, message: '请选择业务类型', trigger: 'blur' }
        ],
        pushUserType: [
          { required: true, message: '请选会员类型', trigger: 'blur' }
        ],
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        content: [{ required: true, message: '请填写内容', trigger: 'blur' }]
      },
      listLoading: true
    }
  },
  watch: {
    rangeCreateDate: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startTime = newVal[0]
          this.listQuery.endTime = newVal[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    },
    latestRangeDate: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.listQuery.startLastDate = newVal[0]
          this.listQuery.endLastDate = newVal[1]
          return
        }
        this.listQuery.startLastDate = ''
        this.listQuery.endLastDate = ''
      }
    }
  },
  created() {
    this.renderData()
  },
  methods: {
    renderData() {
      const that = this
      that.listLoading = true
      pushTextStoreTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleSearch() {
      this.renderData()
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true
      this.thatSelectedUserId = row.id
    },
    handleCreate() {
      this.textOptTitle = '添加推送文案'
      this.formVisible = true
    },
    handlerFormClose() {
      this.formVisible = false
      this.resetForm()
    },
    submitForm() {
      const that = this
      if (!that.validForm()) {
        return
      }

      // that.form.sysPushTextContents = that.languageMapToArraysFilterNullContent()
      that.submitLoading = true
      if (that.form.id) {
        updatePushTextStore(that.form)
          .then(res => {
            that.submitLoading = false
            that.formVisible = false
            that.resetForm()
            that.form.id = ''
            that.renderData()
          })
          .catch(er => {
            that.submitLoading = false
          })
        return
      }
      addPushTextStore(that.form)
        .then(res => {
          that.submitLoading = false
          that.formVisible = false
          that.resetForm()
          that.form.id = ''
          that.renderData()
        })
        .catch(er => {
          that.submitLoading = false
        })
    },
    languageMapToArraysFilterNullContent() {
      const resultArrays = []
      for (const key in this.languageMap) {
        var langObj = this.languageMap[key]
        if (langObj.title && langObj.content) {
          langObj.language = key
          resultArrays.push(langObj)
        }
      }
      return resultArrays
    },
    validForm() {
      if (!this.form.title) {
        this.$opsMessage.fail('标题未录入!')
        return false
      }
      if (!this.form.content) {
        this.$opsMessage.fail('模板内容未录入!')
        return false
      }
      return true
    },
    getSelectedLangItem(value) {
      const language = this.language
      for (let index = 0; index < language.length; index++) {
        const item = language[index]
        if (value === item.value) {
          return Object.assign({ index }, item)
        }
      }
    },
    handleLanguageChange(value) {
      const that = this

      if (!that.form.title || !that.form.content) {
        this.$opsMessage.warn(
          `标题或内容存在空，${
            that.getSelectedLangItem(that.prevSelectedVal).name
          } 拒绝录入处理`
        )
      }

      var selectLanguageMap = that.languageMap[value] || {}
      that.form.title = selectLanguageMap.title
      that.form.content = selectLanguageMap.content
      that.prevSelectedVal = value
    },
    handleLanguageBlur() {
      const language = this.form.language
      const selectedItem = this.getSelectedLangItem(language)
      let languageMapItem = this.languageMap[language]

      if (!languageMapItem) {
        languageMapItem = this.languageMap[language] = {
          language: this.form.language,
          languageName: selectedItem.name,
          title: this.form.title,
          content: this.form.content,
          sort: selectedItem.index
        }
      } else {
        languageMapItem.title = this.form.title
        languageMapItem.content = this.form.content
      }

      if (this.form.title && this.form.content) {
        this.languageNames = this.getLanguageMapNames()
      }
    },
    getLanguageMapNames() {
      const names = []
      for (const key in this.languageMap) {
        const obj = this.languageMap[key]
        if (obj.title && obj.content) {
          names.push(obj.languageName)
        }
      }
      return names
    },
    resetForm() {
      this.languageMap = {}
      this.languageNames = []
      this.prevSelectedVal = 'en'
      this.$refs.form.resetFields()
    },
    handleUpdate(row) {
      this.textOptTitle = '修改推送文案'
      this.formVisible = true
      this.form = Object.assign(this.form, row)
      for (let index = 0; index < row.sysPushTextContents.length; index++) {
        const item = row.sysPushTextContents[index]
        if (index === 0) {
          this.prevSelectedVal = item.language
          this.form.title = item.title
          this.form.content = item.content
        }
        this.languageMap[item.language] = item
      }
      this.languageNames = this.getLanguageMapNames()
    },
    handlePushTextHistory(row) {
      const that = this
      that.pushTextHistoryVisible = true
      that.pushTextHistoryLoading = true
      getPushTextHistory(row.id)
        .then(res => {
          that.pushTextHistory = res.body
          that.pushTextHistoryLoading = false
        })
        .catch(er => {
          that.pushTextHistoryLoading = false
        })
    },
    handleSynchronize() {
      synchronPushText().then(res => {
        this.listLoading = false
        this.$message({
          message: '同步成功',
          type: 'success'
        })
        this.renderData()
      })
    },
    handlerPushTextHistoryClose() {
      this.pushTextHistoryVisible = false
      this.pushTextHistory = []
    }
  }
}
</script>
