<template>
  <div class="container" v-loading="loading">
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-position="right"
      label-width="118px">
      <div class="flexr">
        <div class="content flex1">
          <div class="section-title">Article Detail</div>
          <el-form-item
            prop="articleTypeId"
            label="Article Type:">
            <el-select
              v-model="form.articleTypeId"
              class="add-text"
              placeholder="">
              <el-option
                v-for="(item,index) in options.type"
                :key="index"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="articleTitle"
            label="Article Title:">
            <el-input
              v-model="form.articleTitle"
              class="add-text"
              placeholder=""
              maxlength="100"/>
          </el-form-item>
          <!-- <el-form-item
            label="Posted Date:"
            v-if="isEdit">
            <el-input
              v-model="form.createTime"
              class="add-text"
              readonly/>
          </el-form-item> -->
          <el-form-item
            prop="articleContent"
            label=""
            label-width="0">
            <label
              class="el-form-item__label"
              style="width: 118px;">Article Content:</label>
            <el-input
              v-model="form.articleContent"
              class="area-text"
              type="textarea"
              placeholder=""
              maxlength="5000"
              :autosize="autoSize"/>
          </el-form-item>
        </div>
        <div class="content flex1">
          <div class="section-title">Images & Links</div>
          <el-form-item
            label=""
            label-width="0">
            <label
              class="el-form-item__label"
              style="float: none;">Photos (Max 4 photos and 2mb each)</label>
            <div class="flexcr">
              <el-upload
                class="logo-upload"
                action
                :limit="1"
                :show-file-list="false"
                :file-list="[]"
                :http-request="file => uploadImages(file, index)"
                accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
                v-loading="item.loading"
                v-for="(item, index) in images">
                <div class="uploader-image" v-if="item.articleImagePath">
                  <el-image
                    :src="$imageSrc(item.articleImagePath)"
                    title="Click to update image"/>
                  <i
                    title="Click to delete image"
                    class="uploader-del el-icon-delete"
                    @click.stop="deleteImages(index)"></i>
                </div>
                <i v-else
                  class="el-icon-plus avatar-uploader-icon"
                  title="Click to select file"/>
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item
            label=""
            label-width="0">
            <label
              class="el-form-item__label"
              style="float: none;">LINKS:</label>
            <div style="max-width: 600px; display: grid;">
              <el-table
                class="article-links-table no-border"
                :data="form.articleLinks">
                <el-table-column
                  label="Name Of Link"
                  min-width="120px">
                  <template slot-scope="{row}">
                    <el-input
                      v-model="row.articleLinkName"
                      maxlength="100"/>
                  </template>
                </el-table-column>
                <el-table-column
                  label="Hyperlink"
                  min-width="130px">
                  <template slot-scope="{row}">
                    <el-input
                      v-model="row.articleLink"
                      maxlength="150"/>
                  </template>
                </el-table-column>
                <el-table-column
                  label=""
                  width="90px">
                  <template slot-scope="{row,$index}">
                    <div class="flexc" v-loading="row.loading">
                      <i
                        class="list-item-icon el-icon-remove-outline"
                        style="color: #ED3F3F;"
                        @click="onRemoveLink($index)"/>
                      <i
                        v-if="$index === form.articleLinks.length - 1"
                        class="list-item-icon el-icon-circle-plus-outline"
                        style="color: #82CF08;"
                        @click="addLinkObj"/>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </div>
      </div>
      <div class="content flexcr">
        <div class="buttons">
          <el-button
            @click="onClickCancel"
            type="primary"
            class="cancel-button">
            Cancel
          </el-button>
          <el-button
            @click="onClickSave"
            type="primary">
            Save
          </el-button>
        </div>
        <div
          class="update-by"
          v-if="isEdit">
          <span
            class="add-text"
            :title='"CREATED BY " + form.createdBy + " ON " + form.createdOn'>
            LAST UPDATED BY {{form.updatedBy}} TIMESTAMP: {{form.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import api from '../../api/article.js'
export default {
  data() {
    return {
      loading: false,
      form: {
        articleTypeId: "",
        articleTitle: "",
        articleContent: "",
        articleImagePaths: [],
        articleLinks: [],
        createTime: ""
      },
      options: {
        type: []
      },
      images: [{
        articleImagePath: "",
        loading: false
      }],
      isEdit: false,
      rules: {
        articleTypeId: [{
          message: "Please select article type",
          trigger: "change",
          required: true,
        }],
        articleTitle: [{
          message: "Please input article title",
          trigger: "blur",
          required: true,
        }],
        articleContent: [{
          message: "Please input article content",
          trigger: "blur",
          required: true,
        }],
      },
      autoSize: {
        minRows: 20,
        maxRows: 50
      }
    };
  },
  created() {
    this.loading = true;
    this.addLinkObj();
    if (this.$route.params.id) {
      this.isEdit = true;
    }
    this.getArticleTypeOptions();
  },
  methods: {
    onClickCancel() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/marketing-management/article"
        })
      })
    },
    getArticleTypeOptions() {
      api.getArticleTypeOption().then(res => {
        this.options.type = res.data;
      }).catch(err => {
        this.$message.error(err);
      }).finally(() => {
        if (this.isEdit) {
          this.getArticleDetail()
        } else {
          this.loading = false;
        }
      });
    },
    getArticleDetail() {
      api.viewArticle(this.$route.params.id).then(res => {
        if (res.data) {
          this.form = res.data
          this.images = []
          this.form.articleImagePaths.forEach(item => {
            this.images.push({
              ...item,
              loading: false
            })
          })
          this.addImageObj();
        }
      }).catch(err => {
        this.$message.error(err)
      }).finally(() => {
        this.loading = false;
      })
    },
    addImageObj() {
      if (this.images.length < 4) {
        this.images.push({
          articleImagePath: "",
          loading: false
        })
      }
    },
    uploadImages(file, index) {
      this.images[index].loading = true;
      const formData = new FormData()
      formData.append('file', file.file)
      api.uploadImages(formData).then(res => {
        if (res.data.picturePath) {
          if (!this.images[index].articleImagePath) {
            this.addImageObj();
          }
          this.images[index].articleImagePath = res.data.picturePath
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.images[index].loading = false;
      })
    },
    deleteImages(index) {
      const item = this.images[index];
      if (item.articleImageId) {
        this.$confirm('Confirm delete?', 'Delete', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(res => {
          this.deleteImageById(item.articleImageId, index);
        })
      } else {
        this.images.splice(index, 1);
        this.addImageObj()
      }
    },
    deleteImageById(id, index) {
      this.images[index].loading = true;
      api.deleteArticleImage(id).then(res => {
        this.images.splice(index, 1);
        this.addImageObj()
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
        this.images[index].loading = false;
      })
    },
    addLinkObj() {
      this.form.articleLinks.push({
        loading: false,
        articleLink: "",
        articleLinkName: ""
      })
    },
    onRemoveLink(index) {
      const item = this.form.articleLinks[index];
      if (item.articleLinkId) {
        this.$confirm('Confirm delete?', 'Delete', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(res => {
          this.deleteLinkById(item.articleLinkId, index);
        })
      } else {
        this.form.articleLinks.splice(index, 1);
        if (this.form.articleLinks.length == 0) {
          this.addLinkObj()
        }
      }
    },
    deleteLinkById(id, index) {
      this.form.articleLinks[index].loading = true;
      api.deleteArticleLink(id).then(res => {
        this.form.articleLinks.splice(index, 1);
        if (this.form.articleLinks.length == 0) {
          this.addLinkObj()
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
        this.form.articleLinks[index].loading = false;
      })
    },
    onClickSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const images = this.images.filter(item => item.articleImagePath)
          if (images.length == 0) {
            this.$message({
              message: "Please upload at least one image",
              type: 'error'
            })
            return;
          }
          const links = this.form.articleLinks.filter(item => item.articleLinkName);
          if (links.length == 0) {
            this.$message({
              message: "Please add at least one link",
              type: 'error'
            })
            return;
          }
          const params = {
            ...this.form,
            articleLinks: links,
            articleImagePaths: images
          }
          this.loading = true;
          this.isEdit ? this.updateArticle(params) : this.addArticle(params);
        }
      })
    },
    addArticle(params) {
      api.addArticle(params).then(res => {
        this.$message({
          type: 'success',
          message: "Add successfully"
        });
        this.onClickCancel();
      }).catch(err => {
        this.loading = false;
        this.$message({
          type: 'error',
          message: err
        })
      });
    },
    updateArticle(params) {
      api.updateArticle(params).then(res => {
        this.$message({
          type: 'success',
          message: "Update successfully"
        });
        this.onClickCancel();
      }).catch(err => {
        this.loading = false;
        this.$message({
          type: 'error',
          message: err
        })
      });
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '../../styles/variables.scss';
  .container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  .content {
    min-width: 400px;
    margin: 0 8px 16px;
    padding: 15px 60px;
    border-radius: 6px;
    background-color: white;
  }
  
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 15px;
    user-select: none;
    line-height: 24px;
    font-weight: bold;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100%;
    min-width: 200px;
  }
  
  .area-text {
    width: 100%;
    min-width: 200px;
  }
  
  .add-text ::v-deep .el-textarea__inner,
  .area-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  @media screen and (max-width: 500px) {
    .container {
      padding: 0px;
    }
    .content {
      padding: 15px 30px;
    }
  }
  .logo-upload {
    width: 148px;
    height: 148px;
    position: relative;
    margin-right: 15px;
    margin-bottom: 15px;
    ::v-deep .el-image {
      width: 148px;
      height: 148px;
      border-radius: 6px;
    }
  }
  
  .avatar-uploader-icon {
    width: 148px;
    height: 148px;
    color: #8c939d;
    cursor: pointer;
    font-size: 28px;
    text-align: center;
    line-height: 148px;
    border-radius: 6px;
    border: 1px dashed #d9d9d9;
  }
  
  .uploader-image {
    width: 148px;
    height: 148px;
    text-align: left;
    position: relative;
  }
  
  .uploader-image ::v-deep img {
    object-fit: cover;
  }
  
  .uploader-del {
    right: 4px;
    bottom: 4px;
    color: #fff;
    padding: 5px;
    display: none;
    border-radius: 30px;
    position: absolute;
    background-color: rgba(1,1,1,.4);
  }
  
  .uploader-image:hover .uploader-del {
    display: block;
  }
  
  .article-links-table ::v-deep .el-table__header th {
    color: #606266;
    border: none;
    padding: 10px 0 0;
    font-weight: normal;
    background: transparent;
  }
  .article-links-table ::v-deep td {
    border: none;
    padding: 1px 0;
    background: #fff !important;
  }
  .article-links-table ::v-deep .cell {
    padding: 0px 8px 10px;
  }
  .list-item-icon {
    height: 30px;
    cursor: pointer;
    font-size: 26px;
    font-weight: 500;
    line-height: 30px;
  }
  .list-item-icon + .list-item-icon {
    margin-left: 15px;
  }
</style>