import React, { PureComponent } from 'react';
// import { connect } from 'dva';
import moment from 'moment';
import "moment/locale/zh-cn";
import style from "styled-components";

import { Select, Input, Button, message, Modal, Icon } from 'antd';
// import { Link } from 'dva/router';
import "./zhaoping.less";
import PTable from "../../../components/Pro/PTable";
import Positioning from '../../../assets/images/positioning.png';
import FullTime from '../../../assets/images/full_time.png';
import NumberOfPeople from '../../../assets/images/number_of_people.png';
import BasicRequirements from '../../../assets/images/basic_requirements.png';
import JobResponsibilities from '../../../assets/images/job_responsibilities.png';
import {
  enterpriseGetComJob,//预览，通过职位Id查询
  enterpriseDeleteComJob,//招聘批量删除
  enterpriseUpdateReleaseStatusComJob,//招聘批量状态开关
  enterpriseUpdateReleaseTimeComJob,//招聘批量刷新发布时间
  getDistrictChineseData,//省市区转为中文
} from "../../../services/api";
import { debug } from 'util';

const dateFormat = 'YYYY-MM-DD';
const { Option } = Select;
const { confirm } = Modal;
// @connect(state => ({
//   monitor: state.monitor,
// }))
export default class Employing extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {/**
    * 抽屉需要
    */
      visible: false,
      forceUpdate: false,
      selectedRowIds: [], //需要删除的信息id值集合
      selectedRowKeys: [],
      pageParm: {
        pageSize: '10',
        pageNumber: '1',
        keyword: '',
        releaseStatus: '',

      },
      listPage: {
        positionName: '',//职位名称
        positionNature: '',//职位性质
        positionType: '',//职位类型
        releaseStatus: '',//发布状态
        employPerNum: '',//招聘人数
        province: '',//工作地点所在省份
        city: '',//工作地点所在城市
        area: '',//工作地点所在区/县
        salaryType: '',//薪资类型
        minSalary: '',//薪资下限
        maxSalary: '',//薪资上限
        welfare: "1,2,3",//福利
        welfareRangeContentArrays: [],//福利范围数组
        workTimeType: '',//每天工作时间类型
        workDayType: '',//每周工作天数类型
        jobDesc: '',//岗位职责
        releaseTime: '',//职位发布时间
        workLifeTypeName: '',//工作年限类型
        educationLowName: '',//最低学历
        sexRequireName: '',//性别要求
        minAge: '',//最高年龄
        maxAge: '',//职位名称
        languageName: '',//语言要求
        minHeight: '',//最低身高
        maxHeight: '',//最高身高
        departId: '',//部门ID
        departName: '',//部门名称
        updateTime: '',//更新时间
      },
      province: '',//工作地点所在省份中文
      city: '',//工作地点所在城市中文
      area: '',//工作地点所在区/县中文
      keyword: '',
      releaseStatus: '',
    };

  }

  componentDidMount = () => {
    this.getReleaseStatus();
  }
  getReleaseStatus = () => {
    // console.log("获取状态:", this.state.listPage);
  }
  //重置
  resetting = () => {
    this.setState({
      keyword: '',//输入框的值
      releaseStatus: '',
      forceUpdate: true,
    },
    () => {
      this.search();
    }
  );
  };

  //点击搜索
  search = () => {
    const pageParm = { ...this.state.pageParm };
    pageParm.keyword = this.state.keyword;
    pageParm.releaseStatus = this.state.releaseStatus;
    this.setState({ pageParm });
  }

  //输入框的书写，求职意向
  inputKeywordChange = (e) => {
    this.setState({ keyword: e.target.value.trim() });
  };
  handleChangeReleaseStatus = (value) => {
    this.setState({
      releaseStatus: value,
    });
  };
  // 订单删除
  comJobDelete = (jobIds) => {
    enterpriseDeleteComJob({ jobIds }).then((data) => {
      this.setState({
        selectedRowIds: [],
        selectedRowKeys: [],
      });
      message.info('消息删除成功！');
      this.resetting();
    }, (err) => {
      message.warning('消息删除失败！' + err);
    });
  };
  //发布时间刷新
  updateReleaseTime = (jobId) => {
    enterpriseUpdateReleaseTimeComJob({ jobIds: jobId }).then((data) => {
      message.info('发布时间刷新成功！');
      this.resetting();
    }, (err) => {
      message.warning('发布时间刷新失败！' + err);
    });
  }
  // 批量删除
  handleDeleteList = () => {
    const that = this;
    const keyNumber = this.state.selectedRowIds.length;
    const keyId = this.state.selectedRowIds;
    if (keyNumber <= 0) {
      message.warning('请选择需要删除的信息！');
    } else {
      confirm({
        title: '是否删除所选职位，删除后职位不可找回。是否确认删除？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.comJobDelete(keyId.join(','));
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  };

  //批量刷新
  handleUpdateReleaseTimeList = () => {
    const keyNumber = this.state.selectedRowIds.length;
    const jobIds = this.state.selectedRowIds;
    if (keyNumber <= 0) {
      message.warning('请选择需要更新发布时间的职位！');
    } else {
      confirm({
        title: "刷新后职位的发布时间将被更新，是否确认刷新？",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          enterpriseUpdateReleaseTimeComJob({ jobIds: this.state.selectedRowIds.join(',') }).then((data) => {
         
            this.setState({
              selectedRowIds: [],
              selectedRowKeys: [],
            });
            message.info('发布时间刷新成功！');
            this.resetting();
          }, (err) => {
            message.warning('发布时间刷新失败！' + err);
          });
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };
  //批量关闭开始
  handleUpdateStatus = (status, jobId) => {
    const keyNumber = this.state.selectedRowIds.length;
    const jobIds = this.state.selectedRowIds;
    if (keyNumber <= 0) {
      message.warning('请选择需要更改发布状态的职位！');
    } else {
      let title = "";
      if (status === "1") {
        title = "切换所选职位，如果开启，相关职位将接收简历。是否确认？";
      } else {
        title = "切换所选职位，如果关闭，相关职位将不再接收简历。是否确认？";
      }
      confirm({
        title,
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          // enterpriseUpdateReleaseStatusComJob({ jobIds: this.state.selectedRowIds, releaseStatus: status }).then((data) => {
          enterpriseUpdateReleaseStatusComJob({ jobIds: jobIds.join(','), releaseStatus: status }).then((data) => {
            this.setState({
              selectedRowIds: [],
              selectedRowKeys: [],
            });
            message.info('更改发布状态成功！');
            this.resetting();
          }, (err) => {
            message.warning('更改发布状态失败！' + err);
          });
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };
  handleView = (jobId) => {
    enterpriseGetComJob({ jobId }).then((data) => {
      if (data.data) {
        this.setState({
          listPage: data.data,
        });
        let s1 = '';
        let s2 = '';
        let s3 = '';

        if (this.state.listPage.province) {
          getDistrictChineseData({ regionId: this.state.listPage.province }).then((datas) => {
            s1 = (datas.data.regionName);
          });
        }
        if (this.state.listPage.city) {
          getDistrictChineseData({ regionId: this.state.listPage.city }).then((datt) => {
            s2 = (datt.data.regionName);
          });
        }
        if (this.state.listPage.area) {
          getDistrictChineseData({ regionId: this.state.listPage.area }).then((dats) => {
            s3 = (dats.data.regionName);
          });
        }
        setTimeout(() => {
          this.setState({
            province: s1,
            city: s2,
            area: s3,
          });
        }, 300);
      }
    });
    this.setState({ visible: true });
  }
  handleViewCancel = (e) => {
    this.setState({
      visible: false,
    });
  }
  //表格渲染,多选
  renderTable = () => {
    const selectedRowKey = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys: selectedRowKey,
      onChange: (selectedRowKeys) => {

        this.setState({
          selectedRowKeys
        });
      },
      onSelect: (record, selected, selectedRows) => {
        const selectId = this.state.selectedRowIds;
        if (selected === true) {
          selectId.push(record.jobId);
        } else {
          for (let i = 0; i < selectId.length; i++) {
            if (selectId[i] === record.jobId) {
              selectId.splice(i, 1);
              break;
            }
          }
        }
        this.setState({
          selectedRowIds: selectId
        });
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        let selectId = [];
        if (selected === true) {
          for (let i = 0; i < selectedRows.length; i++) {
            selectId.push(selectedRows[i].jobId);
          }
        } else {
          selectId = [];
          // selectedRowKeys:selectedRowKey
        }
        this.setState({
          selectedRowIds: selectId
        });
      },
    };

    const columns = [
      {
        title: '职位名称',
        dataIndex: 'positionName',
        key: 'positionName',
      },
      {
        title: '部门',
        dataIndex: 'departName',
        key: 'departName',
      },
      {
        title: '收到的简历',
        dataIndex: 'resumeCount',
        key: 'resumeCount',
      },
      {
        title: '浏览量',
        dataIndex: 'browseCount',
        key: 'browseCount',
      },
      {
        title: '状态',
        dataIndex: 'releaseStatusName',
        key: 'releaseStatusName',
      },
      {
        title: '刷新时间',
        dataIndex: 'releaseTime',
        key: 'releaseTime',
      },
      {
        title: '操作',
        dataIndex: 'd',
        key: 'd',
        render: (text, record) => (
          <div>
            <Opton onClick={() => {
              this.props.history.push(`/PersonnelRecruitment/ListContainer/PositionDetail/${record.jobId}/1`);
            }} >修改</Opton>
            <Opton onClick={this.updateReleaseTime.bind(this, record.jobId)} >刷新</Opton>
            <Opton onClick={this.handleView.bind(this, record.jobId)}>预览</Opton>
            <Opton onClick={() => {
              this.props.history.push(`/PersonnelRecruitment/ListContainer/PositionDetail/${record.jobId}/2`);
            }}>复制</Opton>
            {
              record.releaseStatus === "0" ? null : (
                record.releaseStatus === "1" ?
                  <Opton onClick={this.handleUpdateStatus.bind(this, '2', record.jobId)}>关闭</Opton>
                  :
                  <Opton onClick={this.handleUpdateStatus.bind(this, '1', record.jobId)}>开启</Opton>
              )
            }
          </div>
        ),
      }
    ];
    return (
      <PTable
        style={{ marginTop: 20 }}
        columns={columns}
        url="enterpriseComJobPage"
        pageParm={this.state.pageParm}
        rowSelection={rowSelection}
        forceUpdate={this.state.forceUpdate}
        showTotal={total => `共搜素到${total}条记录`}
      />
    );

  };



  render() {

    return (
      <Content>
        {/* 搜索条件面板 */}
        <div className="searchpanel">
          <span>关键字：</span>
          <Input
            style={{ marginBottom: "10px", width: '214px' }}
            onChange={this.inputKeywordChange}
            value={this.state.keyword}
          />
          <span className="post">状态:</span> 
          <Select value={this.state.releaseStatus} style={{ width: '214px',marginRight:'17px' }} onChange={this.handleChangeReleaseStatus}>
            <Option value="">全部</Option>
            <Option value="0">未发布</Option>
            <Option value="1">开启</Option>
            <Option value="2">关闭</Option>
          </Select>
          <Button style={{marginRight:'17px',marginBottom: '16px' }} type="primary" onClick={this.search}>搜索</Button>
          <Button style={{marginBottom: '16px' }} onClick={this.resetting}>重置</Button>
          <div className="btns">
            <Button type="primary"
              onClick={() => {
                this.props.history.push(`/PersonnelRecruitment/ListContainer/PositionDetail/00/1`);
              }}>发布职位</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleUpdateStatus.bind(this, '2')}>批量关闭</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleUpdateStatus.bind(this, '1')}>批量开启</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleUpdateReleaseTimeList}>批量刷新</Button>
            <Button style={{ marginLeft: 8 }} type="danger" ghost onClick={this.handleDeleteList}>批量删除</Button>
          </div>
        </div>
        {this.renderTable()}
        <Modal
          closable={false}
          visible={this.state.visible}
          footer={null}
          width={294}
          onCancel={this.handleViewCancel}
          className="zhaopingmodal"
        >
          <PhoneContainer>
            <div className="zhaoping">
              <div className="content">
                <div className="back">
                  <span>职位详情</span><span className="left"><Icon type="left" /></span>
                </div>

                {/* <div className="title">
                  {this.state.listPage.positionName} <span className="c">【{this.state.listPage.minSalary / 1000}k-{this.state.listPage.maxSalary / 1000}k】</span><span className="r">更新:{moment(this.state.listPage.updateTime).format(dateFormat)}</span>
                </div>
                <div className="local">
                  <span>
                    <img style={{ marginLeft: "0px" }} className="local-icon" src={Positioning} alt="" />
                    {this.state.province}-{this.state.city}-{this.state.area}
                  </span>
                  <span>
                    <img className="local-icon" src={FullTime} alt="" />
                    {this.state.listPage.positionNature === 1 ? "全职" : "兼职"}
                  </span>
                  <span>
                    <img className="local-icon" src={NumberOfPeople} alt="" />
                    {this.state.listPage.employPerNum}
                    人
                  </span>
                </div> */}

                <div className="container local">
                  <div className="secondtitle">
                    {/* <span className="icon">
                      <img src={BasicRequirements} alt="" />
                    </span> */}
                    <span style={{fontSize:'14px'}}>{this.state.listPage.positionName}</span>
                  </div>
                  <div className="item">
                    <span className="l">更新:</span><span className="r">{moment(this.state.listPage.updateTime).format(dateFormat)}</span>
                  </div>
                  <div className="item">
                    <span className="l">薪酬:</span><span className="r">【{this.state.listPage.minSalary / 1000}k-{this.state.listPage.maxSalary / 1000}k】</span>
                  </div>
                  <div className="item">
                    <span className="l">
                    {/* <img style={{ marginLeft: "0px" }} className="local-icon" src={Positioning} alt="" /> */}
                    工作地址
                    :</span><span className="r">{this.state.province}-{this.state.city}-{this.state.area}</span>
                  </div>
                  <div className="item">
                    <span className="l">
                    {/* <img className="local-icon" src={FullTime} alt="" /> */}性质
                    :</span><span className="r">{this.state.listPage.positionNature === 1 ? "全职" : "兼职"}</span>
                  </div>
                  <div className="item">
                    <span className="l">
                    {/* <img className="local-icon" src={NumberOfPeople} alt="" /> */}招聘人数
                    :</span><span className="r">{this.state.listPage.employPerNum}
                    人</span>
                  </div>
                </div>

                <div className="container">
                  <div className="secondtitle">
                    <span className="icon">
                      <img src={BasicRequirements} alt="" />
                    </span>
                    <span>基本要求</span>
                  </div>
                  <div className="item">
                    <span className="l">学历要求:</span><span className="r">{this.state.listPage.educationLowName}</span>
                  </div>
                  <div className="item">
                    <span className="l">工作经验:</span><span className="r">{this.state.listPage.workLifeTypeName}</span>
                  </div>
                  <div className="item">
                    <span className="l">语言要求:</span><span className="r">{this.state.listPage.languageName}</span>
                  </div>
                  <div className="item">
                    <span className="l">性别要求:</span><span className="r">{this.state.listPage.sexRequireName}</span>
                  </div>
                  <div className="item">
                    <span className="l">年龄要求:</span><span className="r">{this.state.listPage.minAge}-{this.state.listPage.maxAge}</span>
                  </div>
                </div>
                <div className="container">
                  <div className="secondtitle bord">
                    <span className="icon">
                      <img src={JobResponsibilities} alt="" />
                    </span>
                    <span>
                      岗位职责
                  </span>
                  </div>
                  <p className="sub">
                    岗位职责:
                  </p>
                  <p className="sub detail">
                    {this.state.listPage.jobDesc}
                  </p>
                </div>
              </div>
            </div>
          </PhoneContainer>
        </Modal>

      </Content >

    );
  }
}

/************************样式************************/

const Content = style.div`{
  font-size: 14px;
  color: rgba(0,0,0,0.65);
  .searchpanel{
     margin-bottom:16px;
    .post{
      margin:0 8px 0 16px;
    }
  }
  // .btns{
  //   margin-top:16px;
  // }
}`;

const Opton = style.span`{
  font-size: 12px;
  color: #0F71FF;
  cursor:pointer;
  margin-right:8px;
}`;

const PhoneContainer = style.div`{
    margin:-24px;
    width:294px;
    height:600px;
    background：rgba(0,0,0,0);
    .detail{
    word-break: break-word;
    }
}`;
