<template>
  <el-drawer size="100%" append-to-body title="推送服务" :visible.sync="viewDrawer">
    <div>
      <div class="content">
        <!--  用户板块  -->
        <div class="content-left relative">
          <avue-crud height="900" ref="crud1" :data="leftUserDataList" :option="leftUserOptions" :page.sync="leftPages"
            @current-change="leftCurrentPageChange" @size-change="leftSizePageChange"
            @selection-change="leftSelectionChange">
            <template slot="menuLeft">
              <div class="leftInput">
                <el-input size="small" v-model="formInline.userName" class="input-with-select" placeholder="用户名">
                  <el-select size="small" v-model="formInline.groupId" slot="prepend" class="selectWidth"
                    placeholder="请选择">
                    <el-option v-for="item in leftServeOptions" :key="item.id" :label="item.groupName"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <el-button size="small" slot="append" class="input-search" @click="leftSearch">搜索</el-button>
                </el-input>
              </div>
            </template>
            <template slot="labelsBase" slot-scope="{row}">
              <TextTooltip :content="row.labelsBase" length="20"></TextTooltip>
            </template>
          </avue-crud>
          <CustomLoading :visible="leftLoading" loading-text="用户数据加载中"></CustomLoading>
        </div>
        <!--  操作  -->
        <div class="content-center">
          <div><el-button type="primary" size="small" @click="changeTabs(0)">匹配政策</el-button></div>
          <div style="margin-top: 30px"><el-button :disabled="leftUserSelections.length > 0 ? false : true"
              type="primary" @click="changeTabs(1)" size="small">匹配岗位</el-button>
          </div>
        </div>
        <!--  列表  -->
        <div class="content-right relative">
          <avue-crud height="900" ref="crud2" :data="rightDataList"
            :option="rightTabs ? rightPostOptions : rightPolicyOptions" :page.sync="rightPages"
            @selection-change="rightSelectionChange">
            <template slot="menuLeft">
              <el-input style="width: 300px" placeholder="搜索岗位" v-show="rightTabs === 1" prefix-icon="el-icon-search"
                @input="searchInputChange" v-model="searchInput" clearable>
              </el-input>
            </template>
            <template slot="labelName" slot-scope="{row}">
              <TextTooltip :content="row.labelName" length="40"></TextTooltip>
            </template>
            <template slot="jobDescription" slot-scope="{row}">
              <TextTooltip :content="row.jobDescription" length="40"></TextTooltip>
            </template>
          </avue-crud>
          <CustomLoading :visible="rightLoading" loading-text="智能分析匹配中"></CustomLoading>
        </div>
      </div>
    </div>
    <div class="content-footer">
      <el-button type="primary" style="width: 80px" size="small" :disabled="pushState" @click="onSubmit">
        {{ pushState ? '推送中...' : rightTabs ? '推送岗位' : '推送政策' }}
      </el-button>
    </div>
  </el-drawer>
</template>

<script>
import {
  getListAllByLabels,
  getListGroupByLabels,
  getServeAllPolicyList,
  getListByids,
  getSearchAll,
  getSearchAllByUserId,
  pushPolicyUserServe,
  pushPostUserServe,
  getListAllByPolicy
} from "@/api/tenant/serve.js";
import TextTooltip from "@/components/text-tooltip/index.vue";
import { debounce } from '@/util/util'
import { DateTime } from "@/util/dateTime";
import CustomLoading from "@/components/Custom-Loading/index.vue";
const pages = { pagerCount: 3, total: 0, size: 10, currentPage: 1 }
const baseOptions = {
  size: 'medium',
  dateBtn: false,
  addBtn: false,
  editBtn: false,
  delBtn: false,
  height: "auto",
  reserveSelection: false,
  border: true,
  columnBtn: false,
  refreshBtn: false,
  menu: false,
  tip: false,
  selection: true,
}
let leftUserOptions = {
  ...baseOptions,
  column: [{
    label: '姓名',
    prop: 'name',
  }, {
    label: '身份证',
    prop: 'idNumber',
  }, {
    label: '手机号',
    prop: 'telphone',
  }, {
    label: '个人标签',
    prop: 'labelsBase',
    slot: true,
  }]
}
let rightPolicyOptions = {
  ...baseOptions,
  column: [{
    label: '政策名称',
    prop: 'name',
  }, {
    label: '政策标签',
    prop: 'labelName',
    slot: true,
  }]
}
let rightPostOptions = {
  ...baseOptions,
  column: [{
    label: '岗位名称',
    prop: 'jobName',
  }, {
    label: '企业名称',
    prop: 'companyName',
  }, {
    label: '岗位描述',
    prop: 'jobDescription',
    slot: true,
  }]
}
export default {
  components: { TextTooltip, CustomLoading },
  data() {
    return {
      formInline: {},
      leftServeOptions: [],
      leftUserDataList: [],
      leftUserPages: {},
      leftUserSelections: [],
      leftPages: Object.assign({}, pages),
      leftUserOptions: Object.assign({}, leftUserOptions),
      leftLoading: false,
      rightLoading: false,
      rightDataList: [],
      rightDataSelections: [],
      rightPages: Object.assign({}, pages),
      rightPolicyOptions: Object.assign({}, rightPolicyOptions),
      rightPostOptions: Object.assign({}, rightPostOptions),
      searchInput: '',
      rightTabs: 0, // 0： 政策， 1： 岗位
      pushState: false,
    }
  },
  props: {
    visible: Boolean,
    rowData: { default: null, type: Function },
    changeVisible: { default: null, type: Function },
  },
  computed: {
    viewDrawer: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  watch: {
    viewDrawer(val) { val ? this.onPageLoad() : this.onPageInit() }
  },
  methods: {
    onPageLoad() {
      console.log('row', this.rowData)
      if (!this.rowData) return
      this.getLeftSignGroupList()
      this.getLeftUserList()
      // this.getRightListPolicy()
    },
    onPageInit() {
      this.formInline = {}
      this.leftServeOptions = []
      this.leftUserDataList = []
      this.leftUserSelections = []
      this.leftUserPages = Object({}, pages)
      this.leftPages = Object.assign({}, pages)
      this.leftUserOptions = Object.assign({}, leftUserOptions)
      this.leftLoading = false
      this.rightLoading = false
      this.rightDataList = []
      this.rightDataSelections = []
      this.rightPages = Object.assign({}, pages)
      this.rightPolicyOptions = Object.assign({}, rightPolicyOptions)
      this.rightPostOptions = Object.assign({}, rightPostOptions)
      this.searchInput = ''
      this.rightTabs = 0 // 0： 政策
      this.pushState = false
      this.$refs.crud1.selectClear()
      this.$refs.crud2.selectClear()
    },
    changeTabs(type) {
      this.rightDataList = []
      this.rightTabs = type
      this.rightDataSelections = []
      this.$message.success('智能分析匹配中');

      type === 0 && this.getRightListPolicy()
      type === 1 && this.getRightSearchByUserId()
    },
    searchInputChange: debounce(function (val) {
      this.getRightSearch()
    }, 1000),
    leftSearch() {
      this.leftPages.currentPage = 1
      this.getLeftUserList('serve')
      console.log('leftpages:', this.leftPages)
    },
    leftCurrentPageChange(current) {
      this.leftPages.currentPage = current
      this.getLeftUserList()
      console.log('leftpages:', this.leftPages)
    },
    leftSizePageChange(current) {
      this.leftPages.size = current
      this.getLeftUserList()
      console.log('leftpages:', this.leftPages)
    },
    leftSelectionChange(val) {
      this.leftUserSelections = val
      console.log(val, '--------------------00000');
    },
    rightSelectionChange(val) {
      this.rightDataSelections = val
    },
    onSubmit() {
      if (!this.leftUserSelections.length) return this.$message.info('请选择推送用户')
      if (!this.rightDataSelections.length) return this.$message.info('请选择推送政策或岗位')
      if (this.rightTabs === 0) {
        this.pushPolicyAndUser()
      } else {
        this.pushPostAndUser()
      }
    },
    groupNameChange() {
      this.getLeftUserList('serve')
    },
    async pushPostAndUser() {
      this.pushState = true
      const createTime = Date.now() + 2000
      // console.log(this.rightDataSelections,);
      let params = {
        serveId: this.rowData.id,
        posts: this.rightDataSelections.map((item) => ({ id: item.id, type: item.type1,jobName: item.jobName })),
        users: this.leftUserSelections.map((item) => ({ idNumber: item.idNumber, talentsId: item.id, userId: item.userId, userName: item.name   }))
      }
      console.log(params,"999999999999999999999999999");
      let resData = await pushPostUserServe(params)
      if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.$message.success('岗位推送成功')
          this.$refs.crud1.selectClear()
          this.$refs.crud2.selectClear()
          this.pushState = false
        }, timed)

      }
    },
    async pushPolicyAndUser() {
      this.pushState = true
      const createTime = Date.now() + 2000
      let params = {
        serveId: this.rowData.id,
        policyIds: this.rightDataSelections.map((item) => item.id),
        users: this.leftUserSelections.map((item) => ({ idNumber: item.idNumber, talentsId: item.id, userId: item.userId, userName: item.name }))
      }
      let resData = await pushPolicyUserServe(params)
      if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.$message.success('政策推送成功')
          this.$refs.crud1.selectClear()
          this.$refs.crud2.selectClear()
          this.pushState = false
        }, timed)
      }
    },
    async getRightSearch() {
      let params = { keywords: this.searchInput || '1' }
      const createTime = Date.now() + 3000
      this.rightLoading = true
      let resData = await getSearchAll(params)
      if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.rightLoading = false
          this.rightDataList = resData.data.data
        }, timed)

      }
    },
    async getRightSearchByUserId() {
      const ids = this.leftUserSelections.map(item => item.userId).join(',');
      const createTime = Date.now() + 3000
      this.rightLoading = true
      let resData = await getSearchAllByUserId({ ids })
      if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.rightLoading = false
          this.rightDataList = resData.data.data
        }, timed)
      }
    },
    async getRightListPolicy() {
      let params = { ids: this.rowData.policyIds }
      const createTime = Date.now() + 3000
      this.rightLoading = true
      let resData = await getListByids(params)
      if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.rightLoading = false
          this.rightDataList = resData.data.data
        }, timed)
      }
    },
    async getLeftUserList(type) {
      const { currentPage, size } = this.leftPages
      const createTime = Date.now() + 3000
      let params = {
        ...this.formInline,
        current: currentPage,
        size,
        labels: this.rowData.talentsNames.join(','),
      }
      console.log('params', params)
      // params.labels = '未分组'
      this.leftLoading = true
      let resData = await getListAllByPolicy(params)
      if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          const { records, total, size, current } = resData.data.data
          this.leftUserDataList = records
          this.leftPages = { total, size, currentPage: current }
          console.log('leftpages:', this.leftPages)
          this.leftLoading = false
        }, timed)

      }
    },
    async getLeftSignGroupList() {
      const arr = this.rowData.talentsNames.map((v) => ({ groupName: v, value: v }))
      this.leftServeOptions = [{ groupName: '全部' }, ...arr]
      // let params = { labels: this.rowData.talentsNames.join(',') }
      // params.labels = '未分组'
      // let resData = await getListAllByPolicy(params)
      // if ( resData.data.code === 200 ) {
      //   this.leftServeOptions = [{groupName: '全部', value: ''}, ...resData.data.data]
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  display: grid;
  grid-template-columns: 1fr 60px 1fr;
  grid-gap: 20px;

  .content-left {}

  .content-center {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }

  .content-right {

    //修改动画的大小  给文字加粗效果
    .right-search {
      width: 100%;
    }

  }

  .leftInput {
    width: 500px;

    .selectWidth {
      width: 160px !important;
    }

    .el-input__inner {
      width: 300px;
    }

    .input-search {
      margin-right: -15px;
      margin-bottom: -10px;
    }
  }

}

/deep/.el-loading-spinner {
  font-size: 80px;
  font-weight: bold;
}

/deep/.el-loading-spinner .circular {
  width: 80px;
  height: 80px;
}

.content-footer {
  float: right;
}

.relative {
  position: relative;
}
</style>
