<template>
  <el-dialog
    :title="$t('pages.appVersionManager.dialog.descriptionList')"
    :visible="true"
    :modal-append-to-body="true"
    :append-to-body="true"
    :before-close="handleClose"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    width="80%"
  >
    <div class="app-container">
      <div class="filter-container">
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          {{ $t('pages.appVersionManager.action.addDescription') }}
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :before-close="handleClose"
        :element-loading-text="$t('pages.appVersionManager.loading')"
        fit
        highlight-current-row
        max-height="350px"
      >
        <el-table-column :label="$t('pages.appVersionManager.table.id')" prop="id" align="center" />
        <el-table-column :label="$t('pages.appVersionManager.table.language')" prop="language" align="center">
          <template slot-scope="scope">
            <span v-for="item in languageOptions" :key="item.value">
              <span v-if="item.value === scope.row.language">{{
                item.name
              }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('pages.appVersionManager.table.description')" prop="updateDescribe" align="center" />
        <el-table-column :label="$t('pages.appVersionManager.table.worshipDescription')" prop="updateWorshipDescribe" align="center" />
        <el-table-column prop="createTime" :label="$t('pages.appVersionManager.table.createTime')" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('pages.appVersionManager.table.actions')" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click.native="handleUpdate(scope.row)"
            >{{ $t('pages.appVersionManager.action.edit') }}</el-button>
            <el-button
              type="text"
              @click.native="removeDescription(scope.row)"
            >{{ $t('pages.appVersionManager.action.delete') }}</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="textOptTitle"
        :visible.sync="formVisible"
        :modal-append-to-body="true"
        :append-to-body="true"
        :before-close="handleDescriptionClose"
        :close-on-click-modal="false"
        :modal="false"
        append-to-bod="true"
        width="450px"
      >
        <div v-loading="submitLoading">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="100px"
            style="margin-left: 15px;"
          >
            <el-form-item :label="$t('pages.appVersionManager.form.language')" prop="language">
              <el-select
                v-model="form.language"
                :placeholder="$t('pages.appVersionManager.placeholder.language')"
                clearable
                style="width: 100%"
                class="filter-item"
                :disabled="form.id !== ''"
              >
                <el-option
                  v-for="item in languageOptions"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('pages.appVersionManager.form.updateDescribe')" prop="updateDescribe">
              <el-input
                v-model.trim="form.updateDescribe"
                :autosize="{ minRows: 5, maxRows: 8 }"
                type="textarea"
                :placeholder="$t('pages.appVersionManager.placeholder.updateDescribe')"
              />
            </el-form-item>
            <el-form-item :label="$t('pages.appVersionManager.form.updateWorshipDescribe')" prop="updateWorshipDescribe">
              <el-input
                v-model.trim="form.updateWorshipDescribe"
                :autosize="{ minRows: 5, maxRows: 8 }"
                type="textarea"
                :placeholder="$t('pages.appVersionManager.placeholder.updateWorshipDescribe')"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm()">{{ $t('pages.appVersionManager.action.save') }}</el-button>
              <el-button @click="handleDescriptionClose()">{{ $t('pages.appVersionManager.action.cancel') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import {
  getAppVersionDescriptionTable,
  addAppVersionDescription,
  updateAppVersionDescription,
  delAppVersionDescription
} from '@/api/app-manager'
import Pagination from '@/components/Pagination'
import { language } from '@/constant/type'
function getFormData() {
  return {
    id: '',
    versionId: '',
    updateDescribe: '',
    updateWorshipDescribe: '',
    language: ''
  }
}
export default {
  name: 'AppUpdateContent',
  components: { Pagination },
  props: {
    versionId: {
      type: String,
      required: true
    }
  },
  data() {
    const validateUpdateDescribe = (rule, value, callback) => {
      if (!value || value.trim().length === 0) {
        callback(new Error(this.$t('pages.appVersionManager.validation.requiredField')))
      } else if (value && value.length > 500) {
        callback(new Error(this.$t('pages.appVersionManager.validation.max500')))
      } else {
        callback()
      }
    }
    return {
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        versionId: ''
      },
      submitLoading: false,
      listLoading: false,
      searchDisabled: false,
      textOptTitle: '',
      formVisible: false,
      form: getFormData(),
      rules: {
        language: [
          { required: true, message: this.$t('pages.appVersionManager.validation.requiredField'), trigger: 'blur' }
        ],
        updateDescribe: [
          { required: true, trigger: 'blur', validator: validateUpdateDescribe }
        ]
      }
    }
  },
  computed: {
    languageOptions() {
      return language.map(item => ({
        ...item,
        name: this.$t(`pages.appVersionManager.language.${item.value}`)
      }))
    }
  },
  watch: {
    versionId: {
      handler(newVal) {
        this.listQuery.versionId = newVal
        this.renderData()
      },
      immediate: true
    }
  },
  methods: {
    renderData() {
      const that = this
      if (!that.listQuery.versionId) {
        return
      }
      that.listLoading = true
      getAppVersionDescriptionTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleCreate() {
      this.textOptTitle = this.$t('pages.appVersionManager.dialog.addDescription')
      this.formVisible = true
      this.form = getFormData()
    },
    handleUpdate(row) {
      this.textOptTitle = this.$t('pages.appVersionManager.dialog.editDescription')
      this.formVisible = true
      this.form.id = row.id
      this.form.versionId = row.versionId
      this.form.updateDescribe = row.updateDescribe
      this.form.updateWorshipDescribe = row.updateWorshipDescribe
      this.form.language = row.language
    },
    handleDescriptionClose() {
      this.formVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
    },
    handleClose() {
      this.$emit('close')
    },
    handleSearch() {
      this.renderData(true)
    },
    loadSearchUser() {
      this.searchDisabled = true
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          that.form.versionId = that.listQuery.versionId
          if (this.form.id === '') {
            addAppVersionDescription(this.form)
              .then(res => {
                if (res.status) {
                  that.$opsMessage.success()
                  that.submitLoading = false
                  that.formVisible = false
                  that.resetForm()
                  that.renderData(true)
                } else {
                  that.$opsMessage.fail(res.errorMsg)
                  that.submitLoading = false
                }
              })
              .catch(er => {
                that.submitLoading = false
                console.error(er)
                this.$emit('fail')
              })
          } else {
            updateAppVersionDescription(this.form)
              .then(res => {
                if (res.status) {
                  that.$opsMessage.success()
                  that.submitLoading = false
                  that.formVisible = false
                  that.resetForm()
                  that.renderData(true)
                } else {
                  that.$opsMessage.fail(res.errorMsg)
                  that.submitLoading = false
                }
              })
              .catch(er => {
                that.submitLoading = false
                console.error(er)
                this.$emit('fail')
              })
          }
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    removeDescription(item) {
      const that = this
      that
        .$confirm(this.$t('pages.appVersionManager.confirm.deleteDescription'), this.$t('pages.appVersionManager.confirm.title'), {
          type: 'warning'
        })
        .then(() => {
          // that.$message({
          //   message: '处理中，请等待结果',
          //   type: 'warning'
          // })
          that.listLoading = true
          delAppVersionDescription(item.id)
            .then(res => {
              that.listLoading = false
              that.$message({
                message: this.$t('pages.appVersionManager.message.deleteSuccess'),
                type: 'success'
              })
              that.renderData()
            })
            .catch(er => {
              console.error(er)
              that.listLoading = false
            })
        })
        .catch(er => {
          console.error(er)
          that.listLoading = false
        })
    }
  }
}
</script>
<style scoped>
.v-modal {
  z-index: 0;
}
</style>
