<template>
  <div class="page">
    <p class="page-name mb">新增栏目</p>
    <el-form class="input-form model" label-width="100px">
      <div class="item-line">
        <el-form-item prop="columnName" label="栏目名称">
          <el-input
            placeholder="请输入栏目名称"
            v-model.trim="form.columnName"
            clearable
            maxlength="15"
            @change="nameChange"
          ></el-input>
        </el-form-item>
        <el-form-item prop="fatherId" label="设置上级">
          <el-cascader
            v-model="form.fatherId"
            :options="columns"
            :props="columnProps"
            clearable></el-cascader>
        </el-form-item>
      </div>
      <div class="item-line">
        <el-form-item prop="typeId" label="栏目类型">
          <el-select v-model="form.typeId" @change="typeChange">
            <el-option
              v-for="item in types"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="pageSize" label="分页条数">
          <el-input-number v-model="form.pageSize" :min="0" class="auto"></el-input-number>
        </el-form-item>
        <el-form-item prop="menuVisible" label="导航菜单可见">
          <el-switch
            v-model="form.menuVisible"
            :active-value="0"
            :inactive-value="1">
          </el-switch>
        </el-form-item>
      </div>
      <div class="line"></div>
      <template v-if="form.typeId === 1 || form.typeId === 4">
        <el-form-item prop="columnBanner" label="栏目banner">
          <el-upload
            class="avatar-uploader avatar-uploader-lg"
            accept=".jpg,.png,.jpeg,.gif"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :show-file-list="false"
            :action="this.api.upload"
            :data="{
              quote: form.columnName,
              site: '粒子研究院中文站点',
              uploader: userName
            }"
          >
            <img v-if="form.columnBanner" :src="form.columnBanner" class="avatar">
            <div class="uploader-default" v-else>
              <img class="plus" src="@/assets/img/plus.png" alt="">
              <p>点击上传</p>
            </div>
            <div slot="tip" class="el-upload__tip">
              <p>请上传1920x500PX，1M以内的jpg，bmp，png格式</p>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="templateId" label="栏目模板">
          <el-select v-model="form.templateId">
            <el-option
              v-for="item in templates"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="listStyleId" label="列表样式">
          <ul class="styles">
            <li>
              <div class="review">
                <img src="@/assets/img/list1.png" alt="">
              </div>
              <el-radio v-model="form.listStyleId" :label="1">图片列表</el-radio>
            </li>
            <li>
              <div class="review">
                <img src="@/assets/img/list2.png" alt="">
              </div>
              <el-radio v-model="form.listStyleId" :label="2">新闻列表</el-radio>
            </li>
            <li>
              <div class="review">
                <img src="@/assets/img/list2.png" alt="">
              </div>
              <el-radio v-model="form.listStyleId" :label="3">出版物列表</el-radio>
            </li>
          </ul>
        </el-form-item>
        <el-form-item prop="detailStyle" label="详情样式">
          <ul class="styles">
            <li>
              <div class="review">
                <img src="@/assets/img/article1.png" alt="">
              </div>
              <el-radio v-model="form.detailStyle" :label="1">视频详情</el-radio>
            </li>
            <li>
              <div class="review">
                <img src="@/assets/img/article2.png" alt="">
              </div>
              <el-radio v-model="form.detailStyle" :label="2">富文本</el-radio>
            </li>
            <li>
              <div class="review">
                <img src="@/assets/img/article3.png" alt="">
              </div>
              <el-radio v-model="form.detailStyle" :label="3">链接</el-radio>
            </li>
          </ul>
        </el-form-item>
      </template>
      <template v-if="form.typeId === 2">
        <el-form-item prop="connectionType" label="连接类型">
          <el-radio-group v-model="form.connectionType">
            <el-radio :label="1">站内链接</el-radio>
            <el-radio :label="2">站外链接</el-radio>
            <el-radio :label="3">其他站点链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="form.connectionType === 1" label="站内链接">
          <el-cascader
            v-model="links"
            :options="columns"
            :props="columnProps"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item v-show="form.connectionType === 2" prop="linkAddress" label="站外链接">
          <el-input
            placeholder="请输入站外链接"
            v-model.trim="form.linkAddress"
            clearable
          ></el-input>
        </el-form-item>
        <template v-if="form.connectionType === 3">
          <el-form-item prop="siteSelection" label="站点选择">
            <el-select v-model="form.siteSelection">
              <el-option
                v-for="item in sites"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="栏目">
            <el-cascader
              :options="links"
              :props="{ checkStrictly: true }"
              clearable></el-cascader>
          </el-form-item>
        </template>
        <el-form-item prop="isOpen" label="新窗口打开">
          <el-switch
            v-model="form.isOpen"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </template>
      <template v-if="form.typeId === 3">
        <el-form-item prop="templateId" label="栏目模板">
          <el-select v-model="form.templateId">
            <el-option
                v-for="item in templates"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="listStyleId" label="列表样式">
          <ul class="styles">
            <li>
              <div class="review">
                <img src="@/assets/img/list1.png" alt="">
              </div>
              <el-radio v-model="form.listStyleId" :label="1">图片列表</el-radio>
            </li>
            <li>
              <div class="review">
                <img src="@/assets/img/list2.png" alt="">
              </div>
              <el-radio v-model="form.listStyleId" :label="2">新闻列表</el-radio>
            </li>
            <li>
              <div class="review">
                <img src="@/assets/img/list2.png" alt="">
              </div>
              <el-radio v-model="form.listStyleId" :label="3">出版物列表</el-radio>
            </li>
          </ul>
        </el-form-item>
      </template>
      <el-form-item v-show="form.typeId === 4" prop="showWithDetails" label="只有一篇文章时，以详情方式展示">
        <el-switch
          v-model="form.showWithDetails"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
    </el-form>
    <div class="btns">
      <el-button type="primary" @click="submit(1)">发布</el-button>
      <el-button @click="preview">预览</el-button>
      <el-button v-if="!isEdit" @click="submit(0)">保存草稿</el-button>
      <el-button @click="$router.back()">取消</el-button>
    </div>
  </div>
</template>
<script>
import util from "@/libs/util";
import ColumnConst from '@/const/column'
import { mapState } from 'vuex'
export default {
    data() {
        return {
          siteId: this.$store.state.content.siteId,
          isEdit: this.$route.query.type === 'edit',
          nameRepeat: false,
          types: ColumnConst.types,
          templates: ColumnConst.templates,
          sites: ColumnConst.sites,
          columns: [],
          columnProps: {
            checkStrictly: true,
            value: 'id',
            label: 'columnName'
          },
          links: [],
          form: {
            siteId: this.$store.state.content.siteId,
            id: this.$route.query.id || '',
            founderId: +this.$store.state.user.userId,
            editorId: +this.$store.state.user.userId,
            fatherId: +this.$route.query.id || 0,
            level: this.$route.query.level || 1,
            columnName: '',
            typeId: 1,
            pageSize: 10,
            menuVisible: 0,
            columnBanner: '',
            templateId: 1,
            listStyleId: 1,
            detailStyle: 1,
            connectionType: 1,
            linkAddress	: '',
            showWithDetails: 0,
            siteSelection: 1,
            status: 1,
            sort: 1,
            isOpen: 1
          },
          submiting: false, // 新增编辑防抖标识
          updateTime: 0
        };
    },
    computed: {
      ...mapState('user', [
        'userName'
      ])
    },
    mounted() {
      this.getList()
      this.isEdit && this.getData()
    },
    watch: {
        // 监听信息是否有更改,有的话页面离开的时候要询问是否要保存
        form: {
          handler(val){
            this.updateTime++
          },
          deep:true
        },
    },
    methods: {
      // 获取栏目列表
      getList() {
        this.$post(this.api.listWithTree, {
          siteId: this.siteId,
          columnName: '',
          templateId: '',
          typeId	: '',
        }).then(({ data }) => {
          this.columns = data
        }).catch(err => {})
      },
      // 获取详情
      getData() {
        this.$post(`${this.api.findColumn}?id=${this.form.id}`).then(({ data }) => {
          this.form = data
        }).catch(err => {})
      },
      // 赋值上级
      setFatherId() {
        
      },
      // 栏目名称判重
      nameChange(){
        const { columnName, level, id } = this.form
        if (columnName && columnName !== this.originalName) {
          this.$post(this.api.sameLevelJudgment, {
            siteId: this.siteId,
            columnName,
            level: +level,
            id: +id || ''
          }).then(res => {
            this.nameRepeat = false
          }).catch(res => {
            this.nameRepeat = true
          })
        }else{
          this.nameRepeat = false
        }
      },
      // 栏目类型回调
      typeChange(val) {

      },
      // 导入前的钩子
      beforeUpload(file) {
        const { size, name } = file
        const ext = name.substring(name.lastIndexOf('.') + 1)
        if (!util.isImg(ext)) {
          this.$message.error('请上传图片！')
          return false
        }
        if (size / 1024 / 1024 > 1) {
          this.$message.error('请上传1M以内的图片！')
          return false
        }
      },
      uploadError(err, file, fileList) {
        this.$message({
          message: "上传出错，请重试！",
          type: "error",
          center: true
        })
      },
      handleExceed(files, fileList) {
        util.errorMsg(`当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`);
      },
      handleRemove(file, fileList) {
        this.form.columnBanner = ''
      },
      uploadSuccess(res) {
        this.form.columnBanner = res.data.url
      },
      // 预览
      preview() {

      },
      // 提交
      submit(status) {
        if (this.submiting) return false
        const { form } = this
        if (!form.columnName) return util.errorMsg('请填写栏目名称')
        if (this.nameRepeat) return util.errorMsg('同级下已存在重复栏目!')
        if (!form.pageSize) return util.errorMsg('请填写分页条数')
        if (typeof form.fatherId	=== 'object') form.fatherId	= form.fatherId[form.fatherId.length - 1]
        if (form.typeId === 2 && form.connectionType !== 2) {
          const { links } = this
          if (!links.length && form.connectionType === 1) return util.errorMsg('请选择站内链接')
          if (!links.length && form.connectionType === 3) return util.errorMsg('请选择栏目')
          form.linkAddress = links.join()
        }
        form.status = status
        this.submiting = true
        if (this.isEdit) {
          delete form.children
          form.editorId = +this.$store.state.user.userId
          this.$post(this.api.updateColumn, form).then(res => {
            util.successMsg("修改成功")
            this.$router.back()
          }).catch(err => {
            this.submiting = false
          })
        } else {
          this.$post(this.api.saveColumn, form).then(res => {
            util.successMsg("创建成功")
            this.$router.back()
          }).catch(err => {
            this.submiting = false
          })
        }
      }
    }
};
</script>

<style lang="scss" scoped>
$upload-width: 220px;
$upload-height: 102px;
$upload-lg-height: 102px;
/deep/ .avatar-uploader {
  .el-upload {
    position: relative;
    width: $upload-width;
    height: $upload-height;
    border: 1px solid #DCDEE0;
    border-radius: 2px;
    cursor: pointer;
    overflow: hidden;
    .uploader-default {
      display: flex;
      height: $upload-height;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      background: #FAFAFA;
      p {
        margin-top: 10px;
        font-size: 14px;
        color: #333;
        line-height: 20px;
      }
    }
  }
  &.avatar-uploader-lg {
    .el-upload {
      width: 100%;
      max-width: 820px;
      height: $upload-lg-height;

      .uploader-default {
        height: $upload-lg-height;
      }
    }
  }
  .avatar {
    display: block;
    width: $upload-width;
    height: $upload-height;
  }
  .avatar-lg {
    display: block;
    width: 100%;
    height: $upload-lg-height;
  }
  .el-upload__tip {
    margin-top: 0;
    p {
      font-size: 12px;
      color: #333;
    }
  }
}
.style-wrap {
  display: flex;
  margin-top: 10px;
  .label {
    margin-right: 30px;
  }
}
.styles {
  display: inline-flex;
  li {
    margin-right: 20px;
    text-align: center;
    &:hover .review {
      border-color: #2962FF;
    }
  }
  .review {
    padding: 18px;
    margin-bottom: 10px;
    border: 1px solid #DCDEE0;
    border-radius: 2px;
  }
}
</style>