<template>
  <div class="container">
    <div class="top">
      <ul class="tab-ul">
        <li :class="['tab-li',{act: default_tab===item.key}]" v-for="item in tabs" :key="item.key" @click="changeTab(item)">{{item.label}}</li>
      </ul>

      <div class="right-side">
        <el-input 
          v-model="searchForm.key_word" 
          :placeholder="default_tab === 5 ? '请输入图表名称' : '请输入指标Id/指标名称'" 
          style="width: 300px"
          @change="changeUser"
          clearable
        >
          <i slot="prefix" class="el-input__icon el-icon-search"/>
        </el-input>
      </div>
    </div>

    <div class="top">
        <div>
          <el-cascader
            v-model="searchForm.classification"
            :options="classificationList"
            :props="{
              value: 'ClassifyId',
              label: 'ClassifyName',
              children: 'Child',
              emitPath: false,
              multiple:true
            }"
            collapse-tags
            :show-all-levels="false"
            :key="default_tab"
            clearable
            filterable
            @change="changeUser"
            placeholder="请选择分类" 
            style="width: 250px;"
          />
          <el-cascader
            v-model="searchForm.user"
            :options="userList"
            :props="{
              value: 'AdminId',
              label: 'RealName',
              children: 'ChildrenList',
              emitPath: false
            }"
            collapse-tags
            :show-all-levels="false"
            clearable
            @change="changeUser"
            filterable
            placeholder="请选择用户" 
            style="margin: 0 20px"
          />
        </div>
        <div>
          <el-button type="primary" @click="editAuthHandle({},'multiple')">批量编辑</el-button>
          <el-button type="primary" @click="edbAuthSetHandle({},'multiple')" v-if="[3,4].includes(default_tab
        )">权限设置</el-button>
        </div>
    </div>
     <el-table
        :data="tableData"
        ref="table"
        element-loading-text="加载中..."
        v-loading="tableLoading"
        border
        style="margin:30px 0"
        @selection-change="selectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          v-for="item in tableColums"
          :key="item.label"
          :label="item.label"
          :prop="item.key"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          align="center"
        >
          <template slot-scope="{row}">
            <template v-if="item.key==='handle'">
              <span class="editsty" @click="edbAuthSetHandle(row)" v-if="[3,4].includes(default_tab
        )">权限设置</span>
              <span class="editsty" @click="editAuthHandle(row)">编辑</span>
            </template>

            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
        
        <div slot="empty" style="padding: 100px 0">
					<img src="~@/assets/img/cus_m/nodata.png" alt="" style="display:block;width:128px;height:128px;margin: 0 auto;">
					<span>暂无数据</span>
				</div>
    </el-table>
    <el-col :span="24" style="height:35px">
      <m-page
        :page_no="page_no"
        :pageSize="pageSize"
        :total="total"
        @handleCurrentChange="pageChange"
      />
    </el-col>

     <!-- 编辑弹窗 -->
    <m-dialog
      :show.sync="isOpenDialog"
      width="650px"
      :title="dialogForm.title"
      @close="isOpenDialog = false"
    >
      <div class="dialog-cont operateauth-dialog-cont">
        <el-form
          ref="formRef"
          label-position="left"
          hide-required-asterisk
          label-width="80px"
          :model="dialogForm"
          :rules="dialogFormRules"
          @close="cancelDialogHandle"
        >
          <el-form-item label="原创建人">
            <span>{{ dialogForm.old_user_name }}</span>
          </el-form-item>
          <el-form-item label="新创建人" prop="new_user">
            <el-cascader
              v-model="dialogForm.new_user"
              :options="userList"
              :props="{
                value: 'AdminId',
                label: 'RealName',
                children: 'ChildrenList',
                emitPath: false
              }"
              collapse-tags
              :show-all-levels="false"
              clearable
              filterable
              placeholder="请选择用户" 
              style="width: 250px"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="dia-bot">
        <el-button
          type="primary"
          style="margin-right: 60px"
          @click="saveHandle"
          >保存</el-button
        >
        <el-button type="primary" plain @click="cancelDialogHandle"
          >取消</el-button
        >
      </div>
    </m-dialog>

    <!-- 指标权限弹窗 -->
    <edbSetDialog
      :isShow.sync="isEdbSetDialog"
      :edbForm="edbForm"
      :users="userList"
      @setSuccess="()=>{$refs.table.clearSelection();selectedArr=[]}"
    />
  </div>
</template>

<script>
import { operateAuthInterface } from '@/api/modules/setApi';
import { customInterence } from '@/api/modules/crmApi';
import mPage from '@/components/mPage';
import mDialog from '@/components/mDialog';
import edbSetDialog from './components/authSetDialog.vue';
export default {
  components: { mPage,mDialog,edbSetDialog },
  computed: {
    tableColums() {
      return this.default_tab === 5 ? [
        { label: '图表名称',key: 'Name' },
        { label: '图分类',key: 'ClassifyName' },
        { label: '创建人',key: 'CreateUserName' },
        { label: '操作',key: 'handle' },
      ] : [
        { label: '指标ID',key: 'Code' },
        { label: '指标名称',key: 'Name' },
        { label: '创建人',key: 'CreateUserName' },
        { label: '操作',key: 'handle' },
      ]
    }
  },
  data() {
    return {
      default_tab: 1,
      tabs:[
        { label: '手工数据指标', key: 1 },
        { label: '钢联化工数据库', key: 2 },
        { label: 'ETA指标库', key: 3 },
        { label: 'ETA预测指标', key: 4 },
        { label: '图库', key: 5 }
      ],
      selectedArr: [],//多选数组
      tableLoading: false,
      tableData:[],
      page_no: 1,
      total: 0,
      pageSize: 10,

      userList: [],
      classificationList:[],
      searchForm: {
        classification:[],
        user: '',
        key_word: ''
      },

      isOpenDialog: false,
      dialogForm: {
        title: '',
        old_user_name: '',
        ids:'',
        new_user: '',
      },
      dialogFormRules: {
        new_user: [
          { required: true, message: '新创建人不能为空', trigger: 'change' }
        ]
      },

      /* 指标权限设置 */
      isEdbSetDialog: false,
      edbForm: {}
    }
  },
  methods: {

    getTableData() {
      this.tableLoading = true;
      let params = {
        Source: this.default_tab,
        UserId: this.searchForm.user || '',
        CurrentIndex: this.page_no,
        PageSize: this.pageSize,
        Keyword: this.searchForm.key_word,
        Classify:this.searchForm.classification.join(',')
      }
			operateAuthInterface.list(params).then(res => {
        this.tableLoading = false;
        if( res.Ret!==200 )return

        const { Data } = res;
        Data.List && Data.List.forEach(_ => {
          _.ModifyTime = _.ModifyTime ? this.$moment(_.ModifyTime).format('YYYY-MM-DD HH:mm:ss') : ''
          _.PublishTime = _.PublishTime ? this.$moment(_.PublishTime).format('YYYY-MM-DD HH:mm:ss') : ''
        })
        this.tableData = Data.List || [];
        this.total=parseInt(Data.Paging.Totals);
			});
    },
    /* 获取用户列表 */
    getUserList() {
      customInterence.getSale({Status: 0,AllEnabled: true}).then(res => {
        if(res.Ret !== 200) return

        this.userList = res.Data.List || [];
      })
    },
    /* 获取分类列表 */
    getClassificationList() {
      operateAuthInterface.getClassificationBySource({Source: this.default_tab}).then(res => {
        if(res.Ret == 200){
          this.classificationList = res.Data.List || []
        }
      })
    },
    
    changeTab({key}) {
      this.default_tab = key;
      this.searchForm.classification=[]
      this.page_no = 1;
      this.getClassificationList()
      this.getTableData();
    },

    pageChange(page) {
      this.page_no = page;
      this.getTableData()
    },

    changeUser() {
      this.page_no = 1;
      this.getTableData();
    },

    /* 复选框选择 */
    selectionChange(val) {
      console.log(val)
      this.selectedArr = val || [];
    },

    /* 编辑 */
    editAuthHandle({DataId,CreateUserName,},type='single') {
      if(type === 'multiple' && !this.selectedArr.length) return this.$message.warning('请至少勾选一个')

      this.dialogForm = {
        title: type === 'multiple' ? '批量编辑权限' : '编辑权限',
        old_user_name: type === 'multiple' ? this.selectedArr[0].CreateUserName : CreateUserName,
        ids: type === 'multiple' ? this.selectedArr.map(_ => _.DataId) : [DataId],
        new_user: ''
      }
      this.isOpenDialog = true;
    },

    async saveHandle() {
      await this.$refs.formRef.validate()

      const res = await operateAuthInterface.authEdit({
        Source: this.default_tab,
        DataIdList: this.dialogForm.ids,
        NewUserId: Number(this.dialogForm.new_user)
      })

      if(res.Ret !== 200) return
      this.$message.success(res.Msg);
      this.cancelDialogHandle();
      this.getTableData();
    },

    /* 指标权限配置 */
    edbAuthSetHandle({DataId,CreateUserId},type='') {
      if(type === 'multiple' && !this.selectedArr.length) return this.$message.warning('请至少勾选一个')
      if(type === 'multiple' && this.selectedArr.some(_ => this.selectedArr[0].CreateUserId!==_.CreateUserId)) return this.$message.warning('所选指标创建人不是同一用户，请重新选择！')

      this.edbForm = {
        title: type === 'multiple' ? '批量权限设置' : '权限设置',
        createId: type === 'multiple' ? this.selectedArr[0].CreateUserId : CreateUserId,
        ids: type === 'multiple' ? this.selectedArr.map(_ => _.DataId) : [DataId],
      }
      this.isEdbSetDialog = true;
      
    },

    cancelDialogHandle() {
      this.$refs.formRef.resetFields();
      this.isOpenDialog = false
    }
  },
  mounted() {
    this.getUserList();
  },
  created(){
    this.getClassificationList()
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: calc(100vh - 160px);
  padding: 20px 30px;
  background: #fff;
  position: relative;
  border: 1px solid #ECECEC;
  border-radius: 4px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-top: 15px;
    .tab-ul,.right-side {
      display: flex;
      margin: 5px 0;
      .tab-li {
        margin-right: 20px;
        min-width: 120px;
        padding: 12px 0;
        text-align: center;
        color: #409EFF;
        border: 1px solid #B3D8FF;
        background: #ECF5FF;
        border-radius: 4px;
        cursor: pointer;
        &.act {
          color: #fff;
          border: 1px solid #409EFF;
          background: #409EFF;
        }
      }
    }
  }

}
.dialog-cont {
  padding-left: 110px;
}
.dia-bot {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
</style>
<style lang="scss">
.operateauth-dialog-cont .el-input {
  width: 100%;
}
</style>