<template>
    <div>
        <el-form>
            <el-card shadow="hover" class="m-b-20">
                <div class="flex-between">
                    <el-page-header @back="goBack" :content="(isEdit ? '更新' : '创建') + '栏目'"></el-page-header>
                    <div>
                        <el-button type="primary" @click="submit">{{ form.id ? "更新" : "创建" }}</el-button>
                    </div>
                </div>
            </el-card>

            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">栏目名称</p>
                    <el-input
                        placeholder="请输入栏目名称"
                        v-model.trim="form.columnName"
                        clearable
                        maxlength="15"
                        class="inline-input"
                        @change="nameChange"
                    ></el-input>
                </div>
            </el-card>
            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">设置上级</p>
                    <el-cascader
                      v-model="form.fatherId"
                      :options="columns"
                      :props="columnProps"
                      clearable></el-cascader>
                </div>
            </el-card>
            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">栏目类型</p>
                    <div class="inline-input">
                        <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>
                    </div>
                </div>
            </el-card>
            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">分页条数</p>
                    <el-input
                        placeholder="请输入分页条数"
                        v-model.trim="form.pageSize"
                        maxlength="15"
                        type="number"
                        style="width: 150px"
                    ></el-input>
                </div>
            </el-card>
            <el-card shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">导航菜单可见</p>
                    <el-switch
                      v-model="form.menuVisible"
                      :active-value="0"
                      :inactive-value="1">
                    </el-switch>
                </div>
            </el-card>
            <template v-if="form.typeId === 1 || form.typeId === 4">
              <el-card shadow="hover" class="mgr20 m-b-20">
                  <div>
                      <p class="m-b-20">栏目banner</p>
                      <el-upload
                          class="avatar-uploader avatar-uploader-lg"
                          accept=".jpg,.png,.jpeg,.gif"
                          :on-remove="handleRemove"
                          :on-error="uploadError"
                          :on-success="uploadSuccess"
                          :before-remove="beforeRemove"
                          :limit="1"
                          :on-exceed="handleExceed"
                          :action="this.api.fileupload"
                          :headers="headers"
                          name="file"
                      >
                          <img v-if="form.columnBanner" :src="form.columnBanner" class="avatar">
                          <div class="uploader-default" v-else>
                              <i class="el-icon-plus"></i>
                              <p>上传banner</p>
                          </div>
                          <div slot="tip" class="el-upload__tip">
                              <p>展示宽度为220，高度140，JPG/PNG/GIF，3MB以内</p>
                          </div>
                      </el-upload>
                  </div>
              </el-card>
              <el-card shadow="hover" class="mgr20 m-b-20">
                  <div>
                      <p class="m-b-20">栏目模板</p>
                      <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>
                      <div class="style-wrap">
                        <p class="label">列表样式</p>
                        <ul class="styles">
                          <li>
                            <el-radio v-model="form.listStyleId" :label="1">图片列表</el-radio>
                          </li>
                          <li>
                            <el-radio v-model="form.listStyleId" :label="2">新闻列表</el-radio>
                          </li>
                          <li>
                            <el-radio v-model="form.listStyleId" :label="3">出版物列表</el-radio>
                          </li>
                        </ul>
                      </div>
                      <div class="style-wrap">
                        <p class="label">详情样式</p>
                        <ul class="styles">
                          <li>
                            <el-radio v-model="form.detailStyle" :label="1">视频详情</el-radio>
                          </li>
                          <li>
                            <el-radio v-model="form.detailStyle" :label="2">富文本</el-radio>
                          </li>
                          <li>
                            <el-radio v-model="form.detailStyle" :label="3">链接</el-radio>
                          </li>
                        </ul>
                      </div>
                  </div>
              </el-card>
            </template>
            <template v-if="form.typeId === 2">
              <el-card shadow="hover" class="mgr20 m-b-20">
                  <div>
                      <p class="m-b-20">连接类型</p>
                      <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>
                  </div>
              </el-card>
              <el-card v-show="form.connectionType === 1" shadow="hover" class="mgr20 m-b-20">
                  <div>
                      <p class="m-b-20">站内链接</p>
                      <el-cascader
                        v-model="links"
                        :options="columns"
                        :props="columnProps"
                        clearable></el-cascader>
                  </div>
              </el-card>
              <el-card v-show="form.connectionType === 2" shadow="hover" class="mgr20 m-b-20">
                  <div>
                      <p class="m-b-20">站外链接</p>
                      <el-input
                        placeholder="请输入站外链接"
                        v-model.trim="form.linkAddress"
                        clearable
                    ></el-input>
                  </div>
              </el-card>
              <template v-if="form.connectionType === 3">
                <el-card shadow="hover" class="mgr20 m-b-20">
                    <div>
                        <p class="m-b-20">站点选择</p>
                        <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>
                    </div>
                </el-card>
                <el-card shadow="hover" class="mgr20 m-b-20">
                    <div>
                        <p class="m-b-20">栏目</p>
                        <el-cascader
                          :options="links"
                          :props="{ checkStrictly: true }"
                          clearable></el-cascader>
                    </div>
                </el-card>
              </template>
            </template>
            <template v-if="form.typeId === 3">
              <el-card shadow="hover" class="mgr20 m-b-20">
                  <div>
                      <p class="m-b-20">栏目模板</p>
                      <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>
                      <div class="style-wrap">
                        <p class="label">列表样式</p>
                        <ul class="styles">
                          <li>
                            <el-radio v-model="form.listStyleId" :label="1">图片列表</el-radio>
                          </li>
                          <li>
                            <el-radio v-model="form.listStyleId" :label="2">新闻列表</el-radio>
                          </li>
                          <li>
                            <el-radio v-model="form.listStyleId" :label="3">出版物列表</el-radio>
                          </li>
                        </ul>
                      </div>
                  </div>
              </el-card>
            </template>
            <el-card v-show="form.typeId === 4" shadow="hover" class="mgr20 m-b-20">
                <div>
                    <p class="m-b-20">只有一篇文章时，以详情方式展示</p>
                    <el-switch
                      v-model="form.showWithDetails"
                      :active-value="1"
                      :inactive-value="0">
                    </el-switch>
                </div>
            </el-card>
        </el-form>
    </div>
</template>
<script>
import util from "@/libs/util";
import ColumnConst from '@/const/column'
import { mapState, mapActions } from "vuex";
export default {
    data() {
        return {
          isEdit: this.$route.query.type === 'edit',
          headers: {},
          nameRepeat: false,
          types: ColumnConst.types,
          templates: ColumnConst.templates,
          sites: ColumnConst.sites,
          columns: [],
          columnProps: {
            checkStrictly: true,
            value: 'id',
            label: 'columnName'
          },
          links: [],
          form: {
            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,
          },
          submiting: false, // 新增编辑防抖标识
          updateTime: 0
        };
    },
    mounted() {
      this.getList()
      this.isEdit && this.getData()
    },
    watch: {
        // 监听信息是否有更改,有的话页面离开的时候要询问是否要保存
        form: {
          handler(val){
            this.updateTime++
          },
          deep:true
        },
    },
    methods: {
      // 获取栏目列表
      getList() {
        this.$post(this.api.listWithTree, {
          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, {
            columnName,
            level: +level,
            id: +id || ''
          }).then(res => {
            this.nameRepeat = false
          }).catch(res => {
            this.nameRepeat = true
          })
        }else{
          this.nameRepeat = false
        }
      },
      // 栏目类型回调
      typeChange(val) {

      },
      uploadError(err, file, fileList) {
        this.$message({
          message: "上传出错，请重试！",
          type: "error",
          center: true
        })
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleExceed(files, fileList) {
        util.errorMsg(`当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`);
      },
      handleRemove(file, fileList) {
        this.form.columnBanner = ''
      },
      uploadSuccess(res) {
        this.form.columnBanner = res.data.filesResult.fileUrl
      },
      // 提交
      submit() {
        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()
        }
        console.log(44, this.links)
        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
          })
        }
      },
      // 返回上一页
      backPage() {
        this.$router.back()
      },
      goBack() {
        const { id } = this.form
        const { updateTime } = this
        // 更改了信息才需要提示
        if ((!this.isEdit && updateTime > 1) || (id && updateTime > 2)) {
          this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
            type: 'warning'
          }).then(() => {
            this.submit()
          }).catch(() => {
            this.backPage()
          })
        } else {
          this.backPage()
        }
      }
    }
};
</script>

<style lang="scss" scoped>
.inline-input {
    width: 500px;
}
$upload-width: 220px;
$upload-height: 140px;
$upload-lg-height: 150px;
/deep/ .avatar-uploader {
    .el-upload {
        position: relative;
        width: $upload-width;
        height: $upload-height;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;

        &:hover {
            border-color: #cb221c;
        }

        .uploader-default {
            display: flex;
            height: $upload-height;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            background: rgba(0, 0, 0, 0.04);

            i {
                font-size: 20px;
                font-weight: bold;
                color: #8c939d;
            }

            p {
                margin-top: 10px;
                font-size: 14px;
                color: rgba(0, 0, 0, 0.65);
                line-height: 1;
            }
        }
    }

    &.avatar-uploader-lg {
        .el-upload {
            width: 100%;
            max-width: 960px;
            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: 14px;
            color: rgba(0, 0, 0, 0.45);
            line-height: 1;

            &:first-child {
                margin-bottom: 5px;
            }
        }
    }
}
.style-wrap {
  display: flex;
  margin-top: 10px;
  .label {
    margin-right: 30px;
  }
}
.styles {
  display: inline-flex;
  li {
    margin-right: 20px;
  }
}
</style>