<template>
  <section style="height: 100%;">
    <ai-list>
      <template slot="title">
        <ai-title title="话术库" :isShowBottomBorder="true"></ai-title>
      </template>
      <template #left>
        <div class="left-tree">
          <div class="tree-title">
            <label>分组</label>
            <el-button icon="iconfont iconAdd" style="height: 28px;line-height: 0;" @click="groupDialog = true">添加分组
            </el-button>
          </div>
          <el-scrollbar style="height: calc(100% - 40px)">
            <el-menu style="height: 100%;" default-active="0" active-text-color="#26f" text-color="#222"
                     mode="vertical">
              <el-menu-item v-for="(item, index) in sortList" :key="index" class="menu-item" @click="currentMenu(item)"
                            :index="index.toString()">
                <label class="item-title">{{ item.name }}</label>
                <el-popover style="width: 30px" placement="left" trigger="click">
                  <div style="display: flex;flex-direction: column;align-items: center;">
                    <div style="cursor: pointer;" @click="editGroup(item, index)">编辑</div>
                    <div style="cursor: pointer;" @click="delteGroup(item, index)">删除</div>
                  </div>
                  <span class="iconfont iconMore" slot="reference"></span>
                </el-popover>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </div>
      </template>
      <template slot="content">
        <ai-search-bar>
          <template slot="left">
            <el-select v-model="search.contentType" placeholder="类型" size="small" clearable @change="getList()">
              <el-option v-for="(item, index) in types" :key="index" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </template>
          <template slot="right">
            <el-input v-model="search.title" class="search-input" size="small"
                      @keyup.enter.native=";(search.current = 1), getList()" placeholder="请输入标题或话术内容或创建人" clearable
                      @clear=";(search.current = 1), (search.title = ''), getList()" suffix-icon="iconfont iconSearch"/>
          </template>
        </ai-search-bar>
        <ai-search-bar>
          <template slot="left">
            <el-button icon="iconfont iconAdd" type="primary" @click="add">添加话术</el-button>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :col-configs="colConfigs" :stripe="true" :total="total" ref="aitableex"
                  style="margin-top: 8px;" :current.sync="search.current" :size.sync="search.size" @getList="getList">\

          <el-table-column slot="content" label="话术内容" align="left" width="280">
            <template slot-scope="{ row }">
              <div class="table-left__wrapper">
                <video :src="row.file && row.file.url" v-if="row.file && row.contentType == 'video'"
                       class="media"></video>
                <img :src="row.file && row.file.url" v-if="row.file && row.contentType == 'image'" class="media"/>
                <audio :src="row.file && row.file.url" v-if="row.file && row.contentType == 'voice'"
                       class="media"></audio>
                <div class="table-left__wrapper--right">
                  <el-tooltip class="item" effect="dark" :content="row.content" placement="top">
                    <div class="table-left__wrapper--text" v-if="row.contentType == 'text'">{{ row.content }}</div>
                  </el-tooltip>
                  <div class="ellipsis" v-if="row.contentType !== 'text'">{{ row.file.name }}</div>
                  <div v-if="row.contentType !== 'text'">{{ row.file.size | size }}KB</div>
                </div>
              </div>
            </template>
          </el-table-column>


          <el-table-column slot="options" label="操作" width="160px" align="center" fixed="right">
            <template slot-scope="{ row }">
              <span class="table-btn" title="编辑" @click="editTrick(row)">编辑</span>
              <span class="table-btn" title="删除" @click="deleteTrick(row)">删除</span>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog :visible.sync="groupDialog" @closed="sortForm = {},sortForm.type=1" width="800px" title="添加分组"
               @onConfirm="onConfirm">
      <el-form size="small" label-width="100px" ref="groupForm" :model="sortForm" :rules="sortRules">
        <el-form-item label="分组名称" prop="name">
          <el-input clearable v-model.trim="sortForm.name" placeholder="请输入..." :maxlength="10" show-word-limit/>
        </el-form-item>
        <!--        <el-form-item label="可见范围" prop="type">-->
        <!--          <el-radio-group v-model="sortForm.type">-->
        <!--            <el-radio label="0">个人话术</el-radio>-->
        <!--            <el-radio label="1">公共话术</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="可用部门" prop="documentName">-->
        <!--          <el-row type="flex">-->
        <!--            <div class="input"></div>-->
        <!--            <ai-person-select :instance="instance" url="/app/appvillagecadres/list" :isMultiple="true"-->
        <!--                              btnText="选择" dialogTitle="选择">-->
        <!--              <template name="option" v-slot:option="{ item }">-->
        <!--                <span class="iconfont iconProlife">{{ item.name }}</span>-->
        <!--                <ai-id mode="show" :show-eyes="false" :value="item.idNumber"/>-->
        <!--              </template>-->
        <!--            </ai-person-select>-->
        <!--          </el-row>-->
        <!--        </el-form-item>-->
      </el-form>
    </ai-dialog>

    <ai-dialog :visible.sync="trickDialog" @close="onClose" @onConfirm="trickConfirm" width="800px" title="添加话术">
      <el-form size="small" label-width="100px" ref="trickFom" :model="trickForm" :rules="trickRules">
        <!--        <el-form-item label="分组" prop="handleResult">-->
        <!--          <ai-select-->
        <!--            v-model="search.type"-->
        <!--            @change="search.current = 1, getList()"-->
        <!--            placeholder="类型"-->
        <!--            :selectList="sortList"-->
        <!--          ></ai-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="标题" prop="title">
          <el-input clearable placeholder="请输入..." v-model="trickForm.title" show-word-limit :maxlength="20"/>
        </el-form-item>
        <el-form-item label="话术类型" prop="contentType">
          <el-radio-group v-model="trickForm.contentType" @change="onChange">
            <el-radio :label="item.value" v-for="(item, index) in types" :key="index">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文本内容" class="el-form-item__textarea" prop="content" v-if="trickForm.contentType == 'text'">
          <span @click="insertNickname" class="el-form-item__btn" type="text">[插入用户昵称]</span>
          <span @click="insertRemark" class="el-form-item__remark" type="text">[插入备注名]</span>
          <el-input type="textarea" v-model="trickForm.content" placeholder="请输入..." :rows="5" show-word-limit
                    :maxlength="255"/>
        </el-form-item>
        <el-form-item :label="compLabel" prop="fileId" v-else>
          <ai-uploader :instance="instance" v-model="fileList" :acceptType="acceptType"
                       :url="'/app/wxcp/upload/uploadFile?type=' + trickForm.contentType" isWechat :fileType="fileType"
                       :limit="1" @change="change"></ai-uploader>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from 'vuex'

export default {
  name: 'AppVerbalTrick',
  label: '话术库',
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
  },
  data() {
    return {
      groupDialog: false,
      trickDialog: false,
      search: {
        current: 1,
        size: 10,
        contentType: '',
      },
      sortForm: {
        name: '',
        type: '1',
      },
      trickForm: {
        title: '',
        contentType: 'text',
        content: '',
        fileId: '',
        mediaId: '',
      },
      row: {},
      current: {},
      sortList: [],
      total: 0,
      tableData: [],
      fileList: [],
    }
  },

  computed: {
    ...mapState(['user']),
    acceptType() {
      return {
        "image": ".jpg,.png,.jpeg",
        "video": ".mp4"
      }[this.trickForm.contentType]
    },
    compLabel() {
      return this.types.find((e) => e.value == this.trickForm.contentType)?.name
    },
    fileType() {
      return this.trickForm.contentType == 'image' ? 'img' : 'file'
    },
    types() {
      return [
        {name: '文本', value: 'text'},
        {name: '图片', value: 'image'},
        {name: '视频', value: 'video'},
        // // {name: "附件", value: "file"},
        // {name: "音频", value: "voice"},
      ]
    },
    trickRules() {
      return {
        title: [{required: true, message: '请输入标题', trigger: 'blur'}],
        contentType: [{required: true, message: '请选择话术类型', trigger: 'change'}],
        content: [{required: true, validator: (rule, value, callback)=>{
            if(this.trickForm.contentType == 'text' && !value){
              return callback("请输入文本内容")
            }else {
              callback()
            }
          }}],
        fileId: [{required: true, validator: (rule, value, callback)=>{
            if(this.trickForm.contentType != 'text' && !value){
              return callback("请上传文件")
            }else {
              callback()
            }
          }}],
      }
    },
    // message() {
    //   return (() => {
    //     if (this.trickForm.contentType == 'text') {
    //       return '请输入文本内容'
    //     } else if (this.trickForm.contentType == 'image') {
    //       return '请上传图片'
    //     } else if (this.trickForm.contentType == 'file') {
    //       return '请上传文件'
    //     } else if (this.trickForm.contentType == 'video') {
    //       return '请上传视频'
    //     } else if (this.trickForm.contentType == 'voice') {
    //       return '请上传音频'
    //     }
    //   })()
    // },
    sortRules() {
      return {
        name: [{required: true, message: '请输入分组名称', trigger: 'blur'}],
        type: [{required: true, message: '请选择可见范围', trigger: 'change'}],
      }
    },
    colConfigs() {
      return [
        {slot: 'type'},
        {slot: 'content'},
        {prop: 'title', label: '标题'},
        {
          prop: 'contentType',
          label: '类型',
          align: 'center',
          render: (h, {row}) => {
            return h('span', {}, this.types.find((e) => row.contentType == e.value)?.name)
          },
        },
        {prop: 'userName', label: '创建人', align: 'center'},
        {prop: 'createTime', label: '创建时间', align: 'center'},
        {slot: 'options', label: '操作', align: 'center'},
      ]
    },
  },

  created() {
    this.getSortList()
  },

  filters: {
    size(size) {
      return (size / 1024).toFixed(1)
    },
  },

  methods: {
    insertNickname() {
      this.trickForm.content += '[用户昵称]'
    },
    insertRemark() {
      this.trickForm.content += '[备注名]'
    },
    onClose() {
      this.trickForm.title = ''
      this.trickForm.content = ''
      this.trickForm.fileId = ''
      this.trickForm.mediaId = ''
      this.trickForm.createdAt = ''
      this.trickForm.contentType = 'text'
      this.fileList = []
    },
    onChange() {
      this.trickForm.fileId = ''
      this.trickForm.content = ''
      this.trickForm.mediaId = ''
      this.trickForm.createdAt = ''
      this.fileList = []
    },
    add() {
      if (this.sortList.length == 0) return this.$message.error('请先添加分组')
      this.$nextTick(() => {
        this.trickDialog = true
      })
    },
    change(e) {
      if(e.length){
        this.trickForm.fileId = e[0].id
        this.trickForm.mediaId = e[0].media.mediaId
        this.trickForm.createdAt = e[0].media.createdAt
      }else {
        this.trickForm.fileId =""
        this.trickForm.mediaId = ""
        this.trickForm.createdAt = ""
      }
    },
    editTrick(row) {
      this.row = row
      this.trickForm = {...row}
      row.file && (this.trickForm.fileId = row.file.id)
      this.$nextTick(() => {
        this.trickDialog = true
      })
      this.fileList.push(row.file)
    },
    deleteTrick(row) {
      this.$confirm('确认要删除吗？').then(() => {
        this.instance
        .post(`/app/wxcp/wxspeechtechnique/delete`, null, {
          params: {
            id: row.id,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success('删除成功')
            this.getList()
          }
        })
      })
    },
    trickConfirm() {
      this.$refs['trickFom'].validate((valid) => {
        if (valid) {
          this.instance
          .post(`/app/wxcp/wxspeechtechnique/addOrUpdate`, {
            ...this.trickForm,
            category: this.current.id,
            userId: this.user.info.id,
          })
          .then((res) => {
            if (res.code == 0) {
              this.trickDialog = false
              this.$message.success(this.trickForm.id ? '编辑成功' : '添加成功')
              this.getList()
            }
          })
        }
      })
    },
    currentMenu(item) {
      this.current = item
      this.getList()
    },
    delteGroup(item, index) {
      this.$confirm('是否要删除？').then(() => {
        this.instance
        .post(`/app/wxcp/wxspeechtechniquecategory/delete`, null, {
          params: {
            id: item.id,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success('删除成功')
            this.getSortList()
          }
        })
      })
    },
    editGroup(item, index) {
      this.sortForm = {...item}
      this.groupDialog = true
    },
    onConfirm() {
      this.$refs['groupForm'].validate((valid) => {
        if (valid) {
          this.instance
          .post(`/app/wxcp/wxspeechtechniquecategory/addOrUpdate`, {
            ...this.sortForm,
          })
          .then((res) => {
            if (res.code == 0) {
              this.groupDialog = false
              this.$message.success(this.sortForm.id ? '编辑成功' : '添加成功')
              this.getSortList()
            }
          })
        }
      })
    },

    getSortList() {
      this.instance
      .post(`/app/wxcp/wxspeechtechniquecategory/listAll`, null, {
        params: {
          // type: 1,
        },
      })
      .then((res) => {
        if (res && res.data.length) {
          this.sortList = res.data
          this.current = res.data[0]
          this.getList()
        }
      })
    },
    getList(item) {
      this.instance
      .post(`/app/wxcp/wxspeechtechnique/list`, null, {
        params: {
          category: this.current.id,
          ...this.search,
          status: 1,
        },
      })
      .then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.left-tree {
  width: 264px;
  background: #fafafb;
  box-shadow: -1px 0px 0px 0px #e5e5e5;
  border-radius: 2px 0px 0px 2px;

  .tree-title {
    height: 40px;
    box-sizing: border-box;
    padding: 0 8px 0 16px;
    background: #eeeff1;
    display: flex;
    align-items: center;
    justify-content: space-between;

    & > label {
      font-size: 14px;
      font-weight: bold;
      color: #222222;
    }
  }

  .tree-item {
    box-sizing: border-box;
    padding: 8px 16px 8px 24px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-right: 2px solid transparent;
  }

  .menu-item {
    height: 40px;
    align-items: center;
    display: flex;
    justify-content: space-between;

    .item-title {
      display: inline-block;
      width: 160px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 14px;
      color: #222222;
    }

    .iconMore {
      cursor: pointer;
    }
  }

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

::v-deep .ai-list__content--right {

  .ai-list__content--right-wrapper {
    min-height: 100%;
  }
}

::v-deep .has-gutter tr {
  height: 40px;
}

::v-deep .el-table__row td {
  height: 68px;
}

// ::v-deep .el-table__row td .cell {
//   width: 240px;
//   height: 44px;
// }

.table-btn {
  font-size: 14px;
  color: #2266ff;
  cursor: pointer;

  &:nth-child(1) {
    margin-right: 16px;
  }
}

.input {
  width: 100%;
  min-height: 32px;
  line-height: 32px;
  border-radius: 4px;
  border: 1px solid #d0d4dc;
  color: #666;
  display: inline-block;
  font-size: inherit;
  cursor: pointer;

  &:after {
    content: '请选择...';
    color: #888888;
    padding-left: 10px;
  }
}

::v-deep .media {
  object-fit: fill;
  width: 40px;
  height: 40px;
  vertical-align: middle;
  box-sizing: content-box;
}

::v-deep .AiPersonSelect {
  & > button {
    background: #f5f5f5;
    border-radius: 0px 2px 2px 0px;
    border: 1px solid #d0d4dc;
    color: #222222;
  }
}

::v-deep .is-active {
  border-right: 2px solid #2266ff;
}
</style>

<style scoped lang="scss">
.el-popper {
  min-width: 76px !important;
}

.table-left__wrapper {
  display: flex;
  align-items: center;

  .table-left__wrapper--text {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .ellipsis {
    width: 170px;
    height: 24px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  img,
  video {
    margin-right: 8px;
  }
}

.el-form-item__textarea {
  position: relative;

  .el-form-item__btn, .el-form-item__remark {
    position: absolute;
    bottom: 12px;
    left: 12px;
    line-height: 1;
    z-index: 1;
    color: #2266FF;
    font-size: 14px;
    user-select: none;
    background: #fff;
    cursor: pointer;
  }

  .el-form-item__remark {
    left: 108px;
  }
}
</style>
