<template>
  <div>
    <div v-if="isExpand && analyticFeedback" style="padding-top: 10px;" v-html="analyticFeedback" />
    <span @click.stop>
      <el-table
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px"
        highlight-current-row
        row-key="rowKey"
        :expand-row-keys="expandRowKeys"
        :header-cell-style="{
          background: '#F7F7F7',
          color: '#4a4a4a',
          'font-size': '14px',
          'font-weight': '500'
        }"
        :cell-style="{ 'font-size': '14px', color: 'rgb(102,102,102)' }"
        size="small"
        show-overflow-tooltip="true"
      >
        <!-- <el-table-column v-if="index === 0 && tabsActive.indexOf('本月重点问题') > -1
        && pageType !== 'edit' ? 'expand' : ''" label="展开" type="expand"> -->
        <el-table-column
          v-for="(item, index) in setColumns(columns)"
          :key="item.headerKey"
          :data-index="index"
          :prop="item.headerKey"
          :align="item.align"
          :label="item.name"
          :type="item.type"
          :min-width="setMinWidth(item)"
          :fixed="isFixed(item, index, columns)"
        >
          <template slot-scope="scope">
            <!--    展开    -->
            <div v-if="item.type === 'expand'">
              <TableExpandRow
                :analytic-feedback="scope.row.analyticFeedback"
                @upAnalyticFeedback="setAnalyticFeedback"
              />
            </div>
            <!--    操作列    -->
            <div v-else-if="item.name === '操作'">
              <div v-if="isExpand">
                <el-button
                  v-if="isShowButton(scope.row, item)"
                  type="text"
                  @click.stop="btnFun({ value: '分析反馈' }, scope)"
                  >分析反馈
                </el-button>
              </div>
              <span v-else>
                <span
                  v-for="(btnItem, btnIndex) in item.defaultValue"
                  :key="btnIndex"
                >
                  <!--另存为-->
                  <span v-if="btnItem.value === '另存为' && isShowButton(scope.row, item)" style="margin-right: 10px">
                    <el-dropdown @command="(command) => saveAsRow(command, scope.row, item)">
                      <el-tooltip
                        class="item"
                        effect="dark"
                        content="将线上问题另存到其他业务线"
                        placement="top"
                        >
                        <el-button type="text">
                        另存
                      </el-button>
                      </el-tooltip>
                      <el-dropdown-menu v-if="subReportInfo" slot="dropdown">
                        <el-dropdown-item v-for="subItem in subReportInfo.filter(subElm => subReportInfoFilter(subElm) )" :key="subItem.id" :command="subItem">
                          {{ subItem.reportName }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </span>
    <!--链接-->
        <span v-else-if="btnItem.value === '链接' && isShowButton(scope.row, item)" @click.stop>
                    <el-popover
                      v-if="scope.row.operationTarget"
                      placement="bottom-start"
                      trigger="hover"
                    >
                      <el-button-group>
                        <el-button size="small" type="info" plain @click="goto(scope.row.operationTarget)">访问链接</el-button>
                        <el-button size="small" type="info" plain @click="btnFun(btnItem, scope)">编辑</el-button>
                        <el-button size="small" type="info" plain @click="scope.row.operationTarget = ''">取消链接</el-button>
                      </el-button-group>
                    <el-button slot="reference" style="margin-right: 10px" type="text">链接</el-button>
                    </el-popover>
                    <el-button
                      v-else
                      style="margin-right: 10px"
                      type="text"
                      @click.stop="btnFun(btnItem, scope)"
                      >链接</el-button>
                  </span>
    <el-button v-else-if="isShowButton(scope.row, item)" style="margin-right: 10px" type="text" @click.stop="btnFun(btnItem, scope)">{{ btnItem.value }}</el-button>
    </span>
    </span>
  </div>
  <div v-else class="edit-wrapper" :style="{ cursor: pageDate && pageDate.status < 20 ? 'pointer' : 'auto' }">
    <!--  <div v-if="editKeys.indexOf(`${scope.row.rowKey}_${index}`) > -1">  -->
    <div v-if="editKeys.indexOf(domKey) > -1 && !item.defaultValue">
      <div v-if="item.displayType === 'Select'">
        <div v-if="item.selectType && item.selectType === 'Time'">
          <el-date-picker v-model="scope.row[item.headerKey]" type="date" style="width: 90%" value-format="yyyy-MM-dd" size="mini" placeholder="选择日期" />
        </div>
        <div v-else-if="item.selectType && item.selectType === 'SinglePeople'">
          <searchPeople :value.sync="scope.row[item.headerKey]" />
        </div>
        <div v-else-if="item.selectType && item.selectType === 'MultiplePeople'">
          <searchPeople :value.sync="scope.row[item.headerKey]" :multiple="true" />
        </div>
        <div v-else-if="item.selectType && item.selectType === 'people'">
          <searchPeople :value.sync="scope.row[item.headerKey]" :multiple="true" />
        </div>
        <el-select v-else v-model="scope.row[item.headerKey]" size="mini" placeholder="请选择" style="width: 80%">
          <el-option v-for="optionItem in item.selectEnum" :key="optionItem" :label="optionItem" :value="optionItem">{{ optionItem }}
          </el-option>
        </el-select>
      </div>
      <el-input v-else-if="item.displayType === 'Texterea'" v-model="scope.row[item.headerKey]" type="textarea" placeholder="请输入" :maxlength="item.name.search(/天数/) > -1 ? 10 : ''" :autosize="{ minRows: item.name.search(/天数/) > -1 ? 1 : 2, maxRows: 30 }" show-word-limit />
      <div v-else-if="item.displayType === 'CascaderSingle'">
        <CascaderSingle v-model="scope.row[item.headerKey]" />
      </div>
      <div v-else-if="item.displayType === 'Cascader'">
        <Cascader v-model="scope.row[item.headerKey]" />
      </div>
      <div v-else-if="item.defaultValue === 'Select'" />
      <el-input v-else v-model="scope.row[item.headerKey]" size="mini" maxlength="100" show-word-limit placeholder="请输入" />
    </div>
    <span v-else-if="item.displayType === 'Text'">{{ item.defaultValue[0].value }}</span>
    <!--  <div v-else class="edit-cell" @click.stop="editLine(scope.row, index)">  -->
    <div v-else class="edit-cell" @click.stop="editLine(scope.row, index)">
      <div v-if="item.displayType === 'Cascader'">
        <CascaderInfo :team-data="scope.row[item.headerKey]" />
      </div>
      <div v-else-if="item.displayType === 'CascaderSingle'">
        <CascaderSingleInfo :team-data="scope.row[item.headerKey]" />
      </div>
      <div v-else-if="item.displayType === 'Select'">
        <!-- 单个人员选择 -->
        <div v-if="item.selectType && item.selectType === 'SinglePeople'">
          <MultiplePeopleInfo :team-data="scope.row[item.headerKey]" />
        </div>
        <!-- 多个人员选择 -->
        <div v-else-if=" item.selectType && item.selectType === 'MultiplePeople'">
          <!-- <searchPeople :value.sync="scope.row[item.headerKey]"
                  :multiple="true" disabled />-->
          <MultiplePeopleInfo :team-data="scope.row[item.headerKey]" />
        </div>
        <!-- 多个人员选择 -->
        <div v-else-if="item.selectType && item.selectType === 'people'">
          <MultiplePeopleInfo :team-data="scope.row[item.headerKey]" />
        </div>
        <div v-else>
          {{ scope.row[item.headerKey] }}
        </div>
      </div>
      <div v-else-if="item.displayType === 'Texterea'" :style="{cursor: item.name === '问题' && scope.row.operationTarget ? 'pointer' : 'auto'}" @click.stop="item.name === '问题' && pageType.search(/edit/) < 0 && goto(scope.row.operationTarget) || editLine(scope.row, index)">
        <TextInfo :text="scope.row[item.headerKey]" />
      </div>
      <div v-else>
        <span v-html="scope.row[item.headerKey]" />
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </span>

        <div class="plus-table-data" :style="{ marginBottom: plusTableDataBottom }" @click.stop>
          <el-button v-if="pageDate && pageDate.status < 20" type="text" @click.stop="addTableData">
            <svg-icon icon-class="data-plus" class="icon" />
            新增
          </el-button>
        </div>
        <span @click.stop>
      <slot name="fixedText" />
      <markingIssues ref="markingIssues" />
      <Analysis ref="Analysis" @upData="upDataAnalysis" />
      <LinkEdit ref="LinkEdit" @change="linkEditChange" />
    </span>
      </div>
</template>

<script>
import _ from 'lodash'
import { uuid10 } from '@/utils'
import Analysis from './Analysis'
import LinkEdit from './LinkEdit'
import Cascader from '../Cascader'
import CascaderInfo from '../CascaderInfo'
import TextInfo from '../TextInfo'
import MultiplePeopleInfo from '../MultiplePeopleInfo'
import TableExpandRow from './TableExpandRow'
import markingIssues from '../markingIssues'
import CascaderSingle from '../CascaderSingle'
import CascaderSingleInfo from '../CascaderSingleInfo'
import searchPeople from '@/components/select/searchPeople' // 人员select
import { updateAnalyticFeedback } from '@/api/qualityMonthlyReport/edit'
import { reportDataBack } from '@/store/modules/monthlyReport/edit/utils.js'
// import { getDeptByKeyWord } from '@/api/qualityMonthlyReport'

export default {
  name: 'MrTable',
  components: {
    Analysis,
    LinkEdit,
    Cascader,
    CascaderInfo,
    searchPeople,
    MultiplePeopleInfo,
    TableExpandRow,
    markingIssues,
    TextInfo,
    CascaderSingle,
    CascaderSingleInfo
  },
  props: {
    plusTableDataBottom: {
      type: String,
      required: false,
      default: () => '18px'
    },
    domKey: {
      type: String,
      required: false,
      default: () => ''
    },
    subTitles: {
      type: Object,
      required: false,
      default: () => null
    },
    columns: {
      type: Array,
      required: false,
      default: () => []
    },
    // 分析反馈时使用的数据
    title: {
      type: String,
      required: false,
      default: () => ''
    },
    tableData: {
      type: Array,
      required: false,
      default: () => []
    }
  },
  data() {
    this.setAnalyticFeedback = _.debounce(this.setAnalyticFeedback, 300)
    return {
      analyticFeedback: '',
      expandRowKeys: [],
      feedbackIndex: null,
      username: localStorage.getItem('username')
    }
  },
  computed: {
    isExpand() {
      return (
        this.pageDate &&
        this.pageDate.status &&
        this.pageDate.status === 30 &&
        ((this.tabsActive.search(/本月重点问题/) > -1 &&
          this.pageType === 'readAll') ||
          (this.pageType === 'read' && this.title === '本月重点问题'))
      )
    },
    selectEnum() {
      return this.$store.state.monthlyReportEdit.selectEnum
    },
    tabPageData() {
      return this.$store.state.monthlyReportEdit.tabPageData
    },
    pageType() {
      return this.$store.state.monthlyReportEdit.pageType
    },
    tabsActive() {
      return this.$store.state.monthlyReportEdit.tabsActive
    },
    pageDate() {
      return this.$store.state.monthlyReportEdit.pageDate
    },
    roleCode() {
      return this.$store.state.monthlyReportEdit.roleCode
    },
    subReportName() {
      return this.$store.state.monthlyReportEdit.subReportName
    },
    subReportInfo() {
      return this.$store.state.monthlyReportEdit.subReportInfo
    },
    editKeys() {
      return this.$store.state.monthlyReportEdit.editKeys
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.setExpandRowKeys()
    })
    setTimeout(() => {
      if (!this.analyticFeedback) {
        this.setAnalyticFeedback()
      }
    }, 3000)
  },
  methods: {
    isEdit() {},
    setMinWidth(item) {
      let width = 80
      if (item.name === '操作') {
        if (item.defaultValue.length) {
          width = item.defaultValue.length * 30
        }
        if (this.isExpand) {
          width = 90
        }
      }
      if (item.name === '定级') {
        width = 70
      }

      if (item.name === '影响') {
        width = 130
      }

      return `${width}px`
    },
    isFixed(item, index, columns) {
      if (item.name === '操作') return 'right'
      return false
    },
    editLine(row, index) {
      // console.log(this.pageDate.status, this.domKey, this.editKeys)
      if (this.pageDate.status < 20) {
        this.$store.commit('monthlyReportEdit/ADD_EDIT_KEYS', this.domKey)
      }
      this.$forceUpdate()
    },
    btnFun(btnItem, scope) {
      this.$store.commit('monthlyReportEdit/INIT_EDIT_KEYS')
      if (btnItem.value === '删除') {
        this.tableData.splice(scope.$index, 1)
      }
      if (btnItem.value === '链接') {
        console.log(scope)
        this.$refs['LinkEdit'].open(scope.row.operationTarget || '', scope.$index)
        // console.log(btnItem, scope, this.columns)
      }
      if (btnItem.value === '标记') {
        this.$refs.markingIssues.modalShow = true
        this.$nextTick(() => {
          this.$refs.markingIssues.openModal({
            title: '标记为重点问题',
            scope,
            columns: this.columns
          })
        })
      }
      if (btnItem.value === '分析反馈') {
        console.log(293, btnItem, scope)
        this.$refs.Analysis.open(scope.row.analyticFeedback, scope.$index)
      }
    },
    // 另存为
    saveAsRow(command, row, item) {
      console.log(414)
      this.$store.commit('monthlyReportEdit/SAVE_AS', {
        tableHeaders: this.columns,
        tableRows: row,
        subReportid: command.id
      })
    },
    // 分析反馈问题更新
    upDataAnalysis({ rowIndex, analyticFeedback }) {
      if (this.pageType.search(/edit/) < 0) {
        console.log(rowIndex, analyticFeedback)
        this.feedbackIndex = rowIndex
        this.tableData[rowIndex].analyticFeedback = _.cloneDeep(
          analyticFeedback
        )
        this.setAnalyticFeedback()
      }
    },
    addTableData() {
      const item = {
        rowKey: uuid10()
      }
      this.columns.forEach((elm) => {
        item[elm.headerKey] = ''
      })
      this.tableData.push(item)
      this.$nextTick(() => {
        this.$store.commit('monthlyReportEdit/GET_ALL_OFFSETTOP')
      })
      this.editLine()
    },
    cascaderChange(value, headerKey, row) {
      console.log(value, headerKey, row)
    },
    // 添加插入
    setColumns(columns) {
      let newColumns = _.cloneDeep(columns)
      if (this.isExpand) {
        newColumns = [
          {
            dataType: 'Single',
            defaultValue: null,
            displayType: 'Cascader',
            name: '',
            align: 'left',
            type: 'expand',
            selectEnum: null,
            selectType: null,
            headerKey: uuid10(6)
          },
          ...newColumns
        ]
        newColumns[1].align = 'left'
      }
      newColumns.forEach((elm) => {
        if (!elm.align) {
          elm.align = 'center'
        }
      })
      // if (this.pageDate.status > 10 && this.tabsActive.indexOf('本月重点问题') < 0) {
      // 非编辑状态，并且不是·本月重点问题·，删除操作按钮
      if (this.pageDate && this.pageDate.status > 10 && !this.isExpand) {
        newColumns.splice(newColumns.length - 1, 1)
      }
      return newColumns
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 0 &&
        this.tabsActive.indexOf('本月重点问题') > -1 &&
        this.pageType.search(/edit/) < 0
      ) {
        return [1, 2]
      } else if (columnIndex === 1) {
        return [0, 0]
      }
    },
    // 查看页面数据分析
    setAnalyticFeedback() {
      if (
        // this.pageType.search(/edit/) < 0 &&
        // this.pageDate.status > 10 &&
        // this.tabsActive.indexOf('本月重点问题') > -1
        this.isExpand
      ) {
        const tabPageData = reportDataBack(_.cloneDeep(this.tabPageData))
        let obj = null
        const run = (arr) => {
          arr.forEach((elm) => {
            if (elm.domKey === this.domKey) {
              console.log(elm)
              obj = _.cloneDeep(elm)
            }
            if (elm.content.length) {
              elm.content.forEach((item) => {
                if (item.domKey === this.domKey) {
                  console.log(elm)
                  obj = _.cloneDeep(elm)
                }
              })
            }
            if (elm.children.length) {
              run(elm.children)
            }
          })
        }
        run(tabPageData.children)
        const params = {
          reportId: this.$route.query.reportId,
          subReportName: this.subReportName,
          feedbackIndex: this.feedbackIndex,
          reportCatalog: obj
        }
        if (this.$route.query.pageType === 'readAll' && obj) {
          params.subReportName = `${obj.title}`
        }
        // console.log(params)
        // 提交数据
        if (obj && obj.content[0].tableRows.length) {
          updateAnalyticFeedback(params).then((res) => {
            if (res.code === 200) {
              this.analyticFeedback = res.data
              if (this.analyticFeedback.search(/yellow/) > -1) {
                this.analyticFeedback = this.analyticFeedback.replace(
                  /yellow/g,
                  '#FAAD14'
                )
              }
              if (this.analyticFeedback.search(/green/) > -1) {
                this.analyticFeedback = this.analyticFeedback.replace(
                  /green/g,
                  '#7ED321'
                )
              }
              // this.analyticFeedback = res.data
            }
          })
        }
      }
    },
    /**
     * 操作按钮是否显示隐藏
     * 1、首先判断 页面 为编辑页面时 展示所有按钮
     * 2、判读分析反馈是否已经提交，已经提交的话，不展示按钮
     * 3、再判断当前表格是否有责任人
     *      有责任人
     *        判断当前用户是否存在负责人中，存在展示按钮，不存在则不展示
     *      无责任人不展示按钮
     * @param row 表格行数据
     * @returns {boolean}
     */
    isShowButton(row) {
      if (
        this.pageType.search(/edit/) > -1 &&
        this.pageDate &&
        this.pageDate.status < 20
      ) {
        return true
      }
      if (row.analyticFeedback && row.analyticFeedback.isCommitted) {
        return false
      }
      // 默认所有情况都展示
      if (this.pageType) {
        return true
      }
      if (this.roleCode === 100 || this.roleCode === 0) return true
      if (this.pageDate.createBy === this.username) return true
      for (let i = 0; i < this.columns.length; i++) {
        const elm = this.columns[i]
        if (elm.name === '责任人') {
          if (!row[elm.headrKey]) return true
          return row[elm.headrKey].indexOf(this.username) > -1
        }
      }
      return false
    },
    setExpandRowKeys() {
      if (this.isExpand && this.tableData && this.tableData.length) {
        this.tableData.forEach((elm) => {
          if (
            elm.analyticFeedback &&
            elm.analyticFeedback.hasOwnProperty('isCommitted') &&
            elm.analyticFeedback.isCommitted &&
            this.expandRowKeys.indexOf(elm.rowKey) < 0
          ) {
            this.expandRowKeys.push(elm.rowKey)
          }
        })
      }
    },
    subReportInfoFilter(elm) {
      const { subReportId } = this.$route.query
      if (this.pageType === 'edit') {
        return `${elm.id}` !== `${subReportId}`
      }
      return this.tabsActive.indexOf(elm.id) < 0
    },
    // 修改链接
    linkEditChange({ rowIndex, addresLink }) {
      console.log(rowIndex, addresLink)
      this.tableData[rowIndex].operationTarget = addresLink
    },
    // 页面跳转
    goto(url) {
      console.log(url)
      url && window.open(url, '_blank')
    }
  }
}
</script>

<style scoped lang="less">
  .edit-wrapper {
    .edit-cell {
      min-height: 23px;
      width: 100%;
    }
  }

  .plus-table-data {
    margin-top: 2px;
  }

  /deep/ .el-table__expand-column {
    border-right: 0;

    .el-icon-arrow-right:before {
      // 这是展开图标
      border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
    }
  }

  /deep/ .el-table__expand-column .cell {
    .el-table__expand-icon {
      .el-icon-arrow-right:before {
        // 这是展开图标
        content: '\e6d9';
        //content: "\e6d8";
      }
    }

    .el-table__expand-icon--expanded {
      // 这是点击后的旋转角度
      //transform: rotate(180deg);
      transform: rotate(0deg);

      .el-icon-arrow-right:before {
        // 这是展开图标
        //content: "\e6d9";
        content: '\e6d8' !important;
      }
    }
  }

  /deep/ .svg-icon {
    width: 1em;
    height: 1em;
  }

  /deep/ .el-table__expanded-cell {
    padding-bottom: 0;
    padding-left: 60px;
  }

  /deep/ .el-button {
    font-weight: 400;
  }

  /deep/ .red {
    color: red;
  }

  /deep/ .green {
    color: green;
  }

  /deep/ .yellow {
    color: yellow;
  }

</style>
