<template>
  <section :class="{ 'dm-wrap': auto }" v-loading="loading">
    <div class="dm-imgtext__tip" v-if="!isPublish">
      <p class="dm-imgtext__tip-item">此处是同步【微信公众平台-草稿箱】中的图文类型草稿，点击“检查同步”可获取最新的草稿和草稿状态；</p>
      <p class="dm-imgtext__tip-item">若在微信公众后台对草稿有进行相关操作，请在此处“检查同步”以获取最新结果；</p>
      <p class="dm-imgtext__tip-item">在此处对草稿进行“修改”/“发布”/“删除”操作，结果都会同步至微信公众平台对应的草稿上。</p>
    </div>
    <div class="dm-imgtext_head" :class="pbSize">
      <div>
        图文消息(共{{ total }}条)
        <el-input v-model="listParams.searchName" clearable class="w200 ml10" placeholder="请输入标题/作者" @change="loadImgTextList"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
        <el-checkbox class="vertical-middle ml0" v-if="$store.state.marketing.isShowSelf && showSelf" v-model="listParams.showSelfFlag" :true-label="1" :false-label="0" label="仅看本人" border @change="loadImgTextList" />
        <el-checkbox class="vertical-middle ml0" v-model="listParams.wxscType" v-if="!isPublish && !isGroupSend" :true-label="3" :false-label="4" border @change="loadImgTextList">
          <el-tooltip content="图文素材已升级为草稿，你可以将所需历史素材转为草稿进行使用；" placement="top">
            <span>仅看历史图文素材</span>
          </el-tooltip>
        </el-checkbox>
      </div>
      <div>
        <el-button type="primary" v-if="$getButtonLimit($buttonCode.marketingAddImgText) && !isPublish" :limit-code="$buttonCode.marketingAddImgText" @click="add">新建图文</el-button>
        <el-button v-if="$getButtonLimit(isPublish ? $buttonCode.marketingPublishSync : $buttonCode.marketingCheckSync) && auto" :limit-code="isPublish ? $buttonCode.marketingPublishSync : $buttonCode.marketingCheckSync" @click="check">检查同步</el-button>
      </div>
    </div>
    <el-radio-group class="dm-imgtext-list" v-model="selectedData.imageTextId" :style="scrollStyle">
      <el-table tooltipEffect="light" :data="textImgList" style="width: 100%" @row-click="rowClick">
        <el-table-column label="" align="center" v-if="radioShow">
          <template slot-scope="scope">
            <div class="label-hidden"><el-radio :disabled="disabled" :label="scope.row.imageTextId"></el-radio></div>
          </template>
        </el-table-column>
        <el-table-column label="图文信息" align="left" min-width="200px">
          <div class="media-info" slot-scope="scope">
            <img width="60" height="60" :src="scope.row.itemList.length ? scope.row.itemList[0].qcloudImageUrl || '' : ''" alt="" />
            <div class="media-title">
              <p>
                标题：<a class="blue" :href="scope.row.itemList.length ? scope.row.itemList[0].mediaUrl || '' : ''" target="_blank">{{ scope.row.itemList.length ? scope.row.itemList[0].titleName || '' : '' }}</a>
              </p>
              <p>
                {{ isPublish ? '图文a_id：' : '图文m_id：' }}
                <el-tooltip v-if="!isPublish && scope.row.draftMediaId" placement="top" :content="scope.row.draftMediaId">
                  <span class="media-id">{{ scope.row.draftMediaId }}</span>
                </el-tooltip>
                <el-tooltip v-else-if="isPublish && scope.row.articleId" placement="top" :content="scope.row.articleId">
                  <span class="media-id">{{ scope.row.articleId }}</span>
                </el-tooltip>
                <span v-else>--</span>
              </p>
            </div>
          </div>
        </el-table-column>
        <el-table-column label="作者" prop="authorName" align="left">
          <template slot-scope="scope">
            <p>{{ scope.row.itemList.length ? scope.row.itemList[0].authorName || '--' : '' }}</p>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" prop="updateTimeStr" align="left">
          <template slot-scope="scope">
            <p class="cell-time">
              <template v-if="scope.row.updateTime">
                {{ formatDateTimeByType(scope.row.updateTime, 'yyyy-MM-dd-HH-mm', true).y }}<br /><span>{{ formatDateTimeByType(scope.row.updateTime, 'yyyy-MM-dd-HH-mm', true).h }}</span>
              </template>
              <template v-else>--</template>
            </p>
          </template>
        </el-table-column>
        <el-table-column min-width="100" align="left" prop="creatorName" label="创建人" :formatter="(row, col, val) => val || '--'" v-if="$store.state.marketing.openFlag"></el-table-column>
        <el-table-column label="发布说明" prop="publishStatus" :formatter="formatPublishStatus" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="left" v-if="auto" min-width="120px">
          <!-- 发布中不能进行编辑、删除、使用等任何操作 -->
          <template slot-scope="scope">
            <template v-if="scope.row.publishStatus == 1 || isPublish">
              <el-button type="text" @click="$router.push('/wechat/check-imgtext/' + scope.row.imageTextId + '?type=' + getWxscType)">查看</el-button>
            </template>
            <template v-if="scope.row.publishStatus != 1">
              <!-- 老图文才有转为草稿 -->
              <!-- 转为草稿就是编辑 -->
              <template v-if="scope.row.oldImageTextFlag && !isPublish">
                <el-button type="text" v-if="scope.row.canEdit !== false" @click="editData(scope.row)">转为草稿</el-button>
              </template>
              <template v-if="!scope.row.oldImageTextFlag && !isPublish">
                <el-button type="text" v-if="$getButtonLimit($buttonCode.marketingEditImgText) && scope.row.canEdit !== false" :limit-code="$buttonCode.marketingEditImgText" @click="editData(scope.row)">编辑</el-button>
                <el-button type="text" v-if="$getButtonLimit($buttonCode.marketingUseImgText) && scope.row.canEdit !== false" :limit-code="$buttonCode.marketingUseImgText" @click="$router.push('/wechat/record/add/' + scope.row.imageTextId)">使用</el-button>
                <el-button v-if="$getButtonLimit($buttonCode.marketingPublishImgText)" :limit-code="$buttonCode.marketingPublishImgText" :loading="scope.row.loading" :disabled="scope.row.loading" @click="onPublic(scope.row)" type="text">发布</el-button>
              </template>
              <dm-delete v-if="$getButtonLimit(isPublish ? $buttonCode.marketingPublishDelImg : $buttonCode.marketingDelImgText) && scope.row.canEdit" width="300" @confirm="delData(scope.row)">
                <div slot="tips" v-if="isPublish">
                  <p class="tips-content"><i class="tipos-icon el-icon-warning"></i>删除后，用户将无法访问此图文页面。请检查当前是否有其他地方正在使用此图文内容，否则将导致发送失败。</p>
                </div>
                <div slot="tips" v-if="!isPublish && !isGroupSend">
                  <p class="tips-content"><i class="tipos-icon el-icon-warning"></i>删除后，用户将无法访问此草稿内容。</p>
                </div>
                <el-button :limit-code="isPublish ? $buttonCode.marketingPublishDelImg : $buttonCode.marketingDelImgText" type="text">删除</el-button>
              </dm-delete>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-radio-group>
    <dm-pagination v-show="textImgList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
    <sync-imgtext :wxsc-type="getWxscType" :show.sync="syncImgTextShow" @syncSuccess="loadImgTextList"></sync-imgtext>
  </section>
</template>

<script>
import { loadImgTextList, deleteImageText, wechatDraftPublish } from '@/service/api/wechatApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
import syncImgtext from './syncImgtext';
export default {
  props: {
    scrollStyle: Object,
    auto: {
      type: Boolean,
      default: true
    },
    radioShow: {
      type: Boolean,
      default: false
    },
    activeId: String,
    pbSize: {
      type: String,
      default: 'pb22'
    },
    showSelfFlag: {
      type: [String, Number],
      default: ''
    },
    showSelf: {
      type: Boolean,
      default: true
    },
    // 是否是群发接口调用
    isGroupSend: {
      type: Boolean,
      default: false
    },
    // 是否是发布列表调用
    isPublish: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    this.loadImgTextList();
  },
  data() {
    return {
      textImgList: [],
      listParams: {
        currentPage: 1,
        pageSize: 20,
        searchName: '',
        showSelfFlag: this.showSelfFlag || '',
        wxscType: 4
      },
      total: 0,
      loading: false,
      syncImgTextShow: false,
      selectedImgTextId: '',
      selectedData: {}
    };
  },
  components: {
    syncImgtext
  },
  computed: {
    getWxscType() {
      return this.isPublish ? 5 : 4;
    }
  },
  watch: {
    activeId(val) {
      this.textImgList.map(v => {
        if (this.activeId === v.imageTextId) {
          this.selectedData = v;
        }
      });
    }
  },
  methods: {
    formatPublishStatus(row, col, val) {
      // 0:成功, 1:发布中，2:原创失败, 3: 常规失败, 4:平台审核不通过, 5:成功后用户删除所有文章, 6: 成功后系统封禁所有文章 100:老图文 , 101:草稿
      const status = new Map();
      // status.set(0, '成功');
      status.set(1, '发布中');
      status.set(2, '原创失败');
      status.set(3, '常规失败');
      status.set(4, '平台审核不通过');
      status.set(5, '成功后用户删除所有文章');
      status.set(6, '成功后系统封禁所有文章');
      // status.set(100, '老图文');
      // status.set(101, '草稿');
      return status.get(typeof val == 'string' ? Number(val) : val) || '--';
    },
    onPublic(row) {
      this.$confirm('你正在将草稿进行“发布”。发布不会占用群发次数，也不会推送给用户。发布后的内容将可添加到自定义菜单、自动回复中。发布成功后，此图文将展示在【图文发布列表】', '发布确认', {
        type: 'warning'
      }).then(() => {
        this.$set(row, 'loading', true);
        wechatDraftPublish({ imageTextId: row.imageTextId })
          .then(res => {
            this.$message.success('成功提交发布，等待发布审核');
            this.loadImgTextList();
          })
          .finally(() => this.$set(row, 'loading', false));
      });
    },
    async loadImgTextList() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      try {
        let params = { ...this.listParams };
        if (this.isGroupSend) {
          params.isGroupSend = 1;
          params.wxscType = 2;
        }
        if (this.isPublish) {
          params.wxscType = 5;
        }
        let res = await loadImgTextList(params);
        if (res.errorCode === 0) {
          // 从页面上过滤itemList为[]的错误数据，原因：微信导入错误
          // eslint-disable-next-line
          this.textImgList = res.result.result  ? res.result.result.filter(v => { return v.itemList ? v.itemList.length !== 0 : true; }) : [];

          this.total = res.result.totalCount;
          this.textImgList.map(v => {
            v.createTimeStr = v.createTime;
            // v.updateTimeStr = v.updateTime;
            if (this.activeId === v.imageTextId) {
              this.selectedData = v;
            }
          });
        }
      } catch (err) {
        console.log(err);
        this.$tips({ type: 'warning', message: '列表请求出错，请稍后再试' });
      }
      this.loading = false;
    },
    reset() {
      this.listParams.searchName = '';
      this.loadImgTextList();
    },
    check() {
      this.syncImgTextShow = true;
    },
    rowClick(row) {
      if (this.disabled) return;
      this.selectedData = row;
      this.$emit('get-data', { imageTextId: row.imageTextId, imageTextWechatId: row.imageTextWechatId });
    },
    add() {
      this.$router.push(`/wechat/editor?type=${this.getWxscType}`);
    },
    editData(row) {
      this.$router.push('/wechat/editor/' + row.imageTextId + '?type=' + this.getWxscType);
    },
    delData(row) {
      deleteImageText({ imageTextId: row.imageTextId })
        .then(res => {
          this.$tips({ type: 'success', message: '删除成功!' });
          if (this.textImgList.length === 1 && this.listParams.currentPage !== 1) {
            this.listParams.currentPage--;
          }
          this.loadImgTextList();
        })
        .catch(err => {
          this.$tips({ type: 'error', message: '删除失败!' });
        });
    },
    handleSizeChange(val) {
      this.listParams.pageSize = val;
      this.loadImgTextList();
    },
    handleCurrentChange(val) {
      this.listParams.currentPage = val;
      this.loadImgTextList();
    },
    formatDateTimeByType
  }
};
</script>

<style lang="scss" scoped>
.dm-imgtext__tip {
  margin-bottom: 20px;
  padding: 10px 18px;
  background: #f7f8fa;
  border-radius: 2px;
  .dm-imgtext__tip-item {
    font-size: 12px;
    font-weight: 400;
    color: #303133;
    line-height: 17px;
    &::before {
      content: '';
      display: inline-block;
      vertical-align: middle;
      margin-right: 6px;
      width: 5px;
      height: 5px;
      border-radius: 5px;
      background: #1890ff;
    }
  }
}
.tips-content {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  .tipos-icon {
    margin-right: 8px;
    vertical-align: text-bottom;
    font-size: 20px;
    color: #faad14;
  }
  margin-bottom: 16px;
  font-size: 14px;
}
.media-info {
  display: flex;
  align-items: center;
  .media-title {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    padding-left: 15px;
    .media-id {
      display: inline-block;
      vertical-align: top;
      width: 160px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.dm-imgtext_head {
  display: flex;
  justify-content: space-between;
}
.dm-imgtext-list {
  width: 100%;
  & > .dm-imgtext-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #e7e7eb;
  }
  .dm-imgtext_left {
    & > img {
      width: 100px;
      height: 100px;
      display: inline-block;
      vertical-align: middle;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    & > div {
      display: inline-block;
      vertical-align: middle;
      line-height: 26px;
      padding-left: 10px;
    }
  }
}
</style>
<style>
.el-message-box__status {
  top: 16px;
}
</style>
