<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" width="500" 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" size="largeXXL" 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"
                     @current-change="rightCurrentPageChange" @size-change="rightSizePageChange"
                     @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>
            <template slot="address" slot-scope="{row}">
              <TextTooltip :content="row.address" length="40"></TextTooltip>
            </template>
          </avue-crud>
          <CustomLoading :visible="rightLoading" size="largeXXL" 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 {
  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,
  align: 'center',
}
let leftUserOptions = {
  ...baseOptions,
  column: [
    {
      label: '机构名称',
      prop: 'companyName',
      fixed: true,
    }, {
      label: '姓名',
      prop: 'name',
      fixed: true,
    }, {
      label: '姓别',
      prop: 'aac004',
      type: 'select',
      dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC004",
      props: {
        label: "dictValue",
        value: "dictKey",
      },
      rules: [
        {
          required: true,
          message: "请输入性别",
          trigger: "blur",
        },
      ],
    }, {
      label: '身份证',
      prop: 'idNumber',
      width: 150,
    }, {
      label: '手机号',
      prop: 'telphone',
    }, {
      label: "求职意愿",
      prop: "willingJob",
    }, {
      label: "民族",
      prop: "aac005",
      type: 'select',
      dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC005",
      props: {
        label: "dictValue",
        value: "dictKey",
      },
      rules: [
        {
          required: true,
          message: "请输入民族",
          trigger: "blur",
        },
      ],
    }, {
      label: "户口性质",
      prop: "aac009",
      type: 'select',
      dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC009",
      props: {
        label: "dictValue",
        value: "dictKey",
      },
      rules: [
        {
          required: true,
          message: "请输入户口性质",
          trigger: "blur",
        },
      ],
    }, {
      label: "户口所在地",
      prop: "aac010",
      width: 150,
    }, {
      label: "文化程度",
      prop: "aac011",
      type: 'select',
      dicUrl: "/api/jobslink-api/system/dict-biz/tadict?code=AAC011",
      props: {
        label: "dictValue",
        value: "dictKey",
      },
      rules: [
        {
          required: true,
          message: "请输入文化程度",
          trigger: "blur",
        },
      ],
    }, {
      label: '个人标签',
      prop: 'labelsBase',
      width: 150,
      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: 'address',
      slot: true,
    }, {
      label: '岗位描述',
      prop: 'jobDescription',
      slot: true,
    }, {
      label: "岗位类型",
      prop: "type1",
      type: "select",
      dicData: [
        {
          value: "0",
          label: "零工岗位",
        },
        {
          value: "1",
          label: "全职岗位",
        },
      ],
      display: false,
      hide: 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('serveCopy')
      console.log('leftpages:', this.leftPages)
    },
    refLeftSearch(userName) {
      this.leftPages.currentPage = 1
      this.formInline.userName = userName
      this.getLeftUserList('serveCopy')
      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)
    },
    rightCurrentPageChange(current) {
      this.rightPages.currentPage = current
      this.rightTabs === 0 && this.getRightListPolicy()
      this.rightTabs === 1 && this.getRightSearchByUserId()
    },
    rightSizePageChange(current) {
      this.rightPages.size = current
      this.rightTabs === 0 && this.getRightListPolicy()
      this.rightTabs === 1 && this.getRightSearchByUserId()
    },
    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('serveCopy')
    },
    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 {currentPage, size} = this.rightPages
      const idNumbers = this.leftUserSelections.map(item => item.idNumber).join(',');
      const willingJobs = this.leftUserSelections.map(item => item.willingJob);
      const createTime = Date.now() + 3000
      this.rightLoading = true
      let params = {
        idNumbers,
        current: currentPage,
        size,
      }
      let paramsBody = {
        willingJobs: willingJobs
      }
      console.log(params, paramsBody)
      let resData = await getSearchAllByUserId(params, paramsBody)
      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.rightLoading = false
          this.rightDataList = records
          this.rightPages = {total, size, currentPage: current}
        }, timed)
      }
    },
    async getRightListPolicy() {
      const {currentPage, size} = this.rightPages
      let params = {
        ids: this.rowData.policyIds,
        current: currentPage,
        size,
      }
      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(() => {
          // const {records, total, size, current} = resData.data.data
          this.rightLoading = false
          // this.rightDataList = records
          // this.rightPages = {total, size, currentPage: current}
          this.rightPages = {total: resData.data.data.length, currentPage: 1}
          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(','),
        talentsGroupId: this.rowData.talentsGroupId
      }
      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: calc(50% - 40px) 80px  calc(50% - 80px);
  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>
