<template>
  <el-drawer size="100%" append-to-body title="推送服务" :visible.sync="viewDrawer">
    <div>
      <div class="push-header">
        <div>
          <el-button type="primary" size="small" @click="changeTabs(0)">匹配政策</el-button>
          <el-button type="primary" @click="changeTabs(1)" size="small">匹配岗位</el-button>
          <el-input style="width: 300px; margin-left: 15px" placeholder="搜索岗位" v-show="rightTabs === 1" size="small"
            prefix-icon="el-icon-search" @input="searchInputChange" v-model="searchInput" clearable>
          </el-input>
        </div>
        <div>
          <el-button type="primary" style="width: 110px" size="small" v-show="visibleTip" @click="informationPush">
            推送温馨提示
          </el-button>
          <el-button type="primary" style="width: 80px" size="small" :disabled="pushState" @click="onSubmit">
            {{ pushState ? '推送中...' : rightTabs ? '推送岗位' : '推送政策' }}
          </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="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="智能分析匹配中...">
          <div class="loading-box">
            <div class="row-loading">
              <span>结构化数据匹配:地理位置、学历、薪资要求</span>
              <img v-if="progress < 1" class="imgcorrect" src="/img/correct1.png">
              <img v-else class="imgcorrect" src="/img/correct2.png">
            </div>
            <div class="row-loading">
              <span>非结构化数据:工作经历和简历、工作岗位和招聘岗位 相似度计算</span>
              <img v-if="progress < 2" class="imgcorrect" src="/img/correct1.png">
              <img v-else class="imgcorrect" src="/img/correct2.png">
            </div>
          </div>
        </CustomLoading>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {
  getListByids,
  getSearchAll,
  getSearchAllByUserId,
  pushPolicyUserServe,
  pushPostUserServe,
  getListAllByPolicy, phoneUpdate,
  getMsgContent,
  pushMsg
} 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 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 {
      leftUserSelections: [],
      rightDataList: [],
      rightLoading: false,
      rightTabs: 0, // 0： 政策， 1： 岗位
      rightPages: Object.assign({}, pages),
      rightPolicyOptions: Object.assign({}, rightPolicyOptions),
      rightPostOptions: Object.assign({}, rightPostOptions),
      rightDataSelections: [],
      searchInput: '',
      pushState: false,
      progress: 0,
      timer: null,
    }
  },
  props: {
    visible: Boolean,
    rowData: { default: null, type: Function },
    phoneItem: { default: {}, type: Object },
    changeVisible: { default: null, type: Function },
    selectInfo: {
      type: Object,
      default: () => {
      },
    },
  },
  computed: {
    viewDrawer: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
    visibleTip: {
      get() {
        let name = this.selectInfo ? this.selectInfo.name : null;
        if (name) name = name.trim()
        console.log(name)
        if (['潜在就业困难人员','潜在就业见习申请人员', '潜在登记失业人员', "潜在的就业困难退出人员"].some(item => item === name)) {
          return true
        }
        return false
      }
    }
  },
  methods: {
    async informationPush() {
      let resData = await getMsgContent({serveId: this.rowData.id})
      if (resData.status === 200 && resData.data.code === 200) {
        const data = resData.data
        this.$confirm(data.data, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async (type) => {
          if (type === 'confirm') {
            pushMsg({
              serveUserId: this.phoneItem.serveUserId,
              id: this.phoneItem.id
            }).then((res) => {
              this.$message.success('推送成功');
            }).cache(() => {
              this.$message.error('推送失败');
            })
          }
        })
      } else {
        this.$message.error('获取模板失败');
      }
    },
    changeTabs(type) {
      this.rightDataList = []
      this.rightTabs = type
      this.rightDataSelections = []
      type === 0 && this.getRightListPolicy()
      if (type === 1) {
        this.$message.success('智能分析匹配中');
        this.getRightSearchByUserId()
      }
    },
    upDateUser(user) {
      this.leftUserSelections = [user]
    },
    searchInputChange: debounce(function (val) {
      this.getRightSearch()
    }, 1000),
    refLeftSearch(name) {
    },
    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()
    },
    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()
      }
    },
    async pushPostAndUser() {
      this.pushState = true
      const createTime = Date.now() + 2000
      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
        }))
      }
       // 处理错误的时候 状态不会改
      await pushPostUserServe(params).then(resData => {
        // 成功的时候
        if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.$message.success('岗位推送成功')
          this.$refs.crud2.selectClear()
          this.pushState = false
        }, timed)
      }
      }).catch(err => {
        this.pushState = false
        console.log(err, 'err')
      })
      // 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.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
        }))
      }
      // 处理错误的时候 状态不会改
      await pushPolicyUserServe(params).then(resData => {
        if (resData.data.code === 200) {
        const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        setTimeout(() => {
          this.$message.success('政策推送成功')
          this.$refs.crud2.selectClear()
          this.pushState = false
        }, timed)
      }
      }).catch(err => {
        this.pushState = false
        console.log(err, 'err')
      })
      // 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.crud2.selectClear()
      //     this.pushState = false
      //   }, timed)
      // }
    },
    async getRightSearch() {
      this.progress = 0
      let params = { keywords: this.searchInput || '1' }
      const createTime = Date.now() + 4000
      this.rightLoading = true
      let resData = await getSearchAll(params)

      if (resData.data.code === 200) {
        this.setProgress().then(() => {
          setTimeout(() => {
            this.rightLoading = false
            this.rightDataList = resData.data.data
            this.rightPages = { total: 10, currentPage: 1 }
          }, 200)
        })
        // const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        // setTimeout(() => {
        //   this.rightLoading = false
        //   this.rightDataList = resData.data.data
        //   this.rightPages = {total: 10, currentPage: 1}
        // }, timed)
      }
    },
    async getRightListPolicy() {
      this.searchInput = ''
      this.progress = 0
      const { currentPage, size } = this.rightPages
      let params = {
        ids: this.rowData.policyIds,
        current: currentPage,
        size,
      }
      // const createTime = Date.now() + 4000
      // this.rightLoading = true
      let resData = await getListByids(params)
      if (resData.data.code === 200) {
        // this.setProgress().then(() => {
        //   setTimeout(() => {
        // this.rightLoading = false
        this.rightPages = { total: resData.data.data.length, currentPage: 1 }
        this.rightDataList = resData.data.data
        //   }, 200)
        // })
        // const timed = createTime - Date.now() > 0 ? createTime - Date.now() : 0
        // setTimeout(() => {
        //
        // }, timed)
      }
    },
    async getRightSearchByUserId() {
      this.progress = 0
      this.searchInput = ''
      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() + 4000
      this.rightLoading = true
      let params = {
        idNumbers,
        current: currentPage,
        size,
      }
      let paramsBody = {
        willingJobs: willingJobs
      }
      let resData = await getSearchAllByUserId(params, paramsBody)
      if (resData.data.code === 200) {
        this.setProgress().then(() => {
          setTimeout(() => {
            const { records, total, size, current } = resData.data.data
            this.rightLoading = false
            this.rightDataList = records
            this.rightPages = { total, size, currentPage: current }
          }, 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)
      }
    },
    setProgress(beforResolve) {
      return new Promise((resolve) => {
        const time = (Math.random() * 1000) + 500
        this.timer = setTimeout(() => {
          this.progress += 1
          if (this.progress >= 2) {
            clearTimeout(this.timer)
            resolve()
            beforResolve()
          } else {
            return this.setProgress(resolve)
          }
        }, time)
      })
    }
  }
}
</script>

<style scoped>
.push-header {
  display: flex;
  justify-content: space-between;
}

.loading-box {
  min-width: 600px;
}

.row-loading {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #666666;
  margin-top: 10px;
}

.imgcorrect {
  width: 20px;
  height: 20px;
}
</style>
