import {
  observable,
  action
} from "mobx";
import HrmBaseStore from "./baseStore";
import {
  message,
  Button
} from 'antd';
import {
  WeaSelect,
  WeaLocaleProvider,
  WeaTools
} from 'ecCom';
import {
  WeaTableNew
} from "comsMobx";
import * as api from "../apis/dailyReport";
import find from 'lodash/find';
import filter from 'lodash/filter';
import flattenDeep from 'lodash/flattenDeep';
import {addContentPath} from '../util/index.js'
const {
  TableStore
} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

export class HrmAttendanceDailyReport extends HrmBaseStore {
  /********************* unobservable list *********************/
  weekdays = this.getLocale().lang.format.weekdays;
  radioGroupVal = {}
  displayColumnsDef = [];
  selectedSerial = '';
  /********************* unobservable list *********************/

  /********************* dialog info setting *********************/

  /********************* dialog info setting *********************/

  /********************* observable list *********************/
  @observable spinning = false;
  @observable spinTip = '';
  @observable pageIndex = 1;
  @observable pageSize = 10;
  @observable total = 0;
  @observable radioGroupConfig = [];
  @observable table = {
    columns: [],
    datas: []
  }
  @observable showColumns = [null, null];
  @observable displayColumns = [];
  @observable holidays = [];
  @observable showHasNotAccount = false;
  @observable detailInfo = {};
  @observable detailTable = new TableStore();
  @observable dialogParams = {
    moduleName: 'hrm',
    visible: false,
    style: {
      width: 700,
      height: 452
    },
    title: '',
    onCancel: () => this.dialogParams.visible = false
  };
  @observable hasOnlyTable = false; //判断是否只包含列表
  /********************* observable list *********************/

  /********************* computed list *********************/
  /********************* computed list *********************/

  /********************* action list *********************/
  clearData = () => {
    this.pageIndex = 1;
    this.pageSize = 10;
    this.total = 0;
    this.radioGroupVal = {};
    this.showHasNotAccount = false;
    this.displayColumns = [];
    this.showColumns = [null, null];
  };

  getQueryParams = (pageIndex, pageSize) => {
    this.pageIndex = pageIndex || 1;
    const params = {
      pageIndex: this.pageIndex,
      ...this.radioGroupVal,
      isNoAccount: this.showHasNotAccount ? '1' : '0',
      attendanceSerial: this.selectedSerial || ''
    }

    pageSize && Object.assign(params, {pageSize});
    return params;
  }

  getShowColumns = () => {
    return filter(this.toJS(this.showColumns), d => d != null).join(',');
  }

  @action init = () => {
    this.clearData()
    this.containerInitFinished.authorized = true;
    this.containerInitFinished.init = true;
    api.getSearchCondition().then(data => {
      if (data.status === '1') {
        this.displayColumnsDef = flattenDeep(data.showColumns);
        this.generateRadioGroupConfig(data);
      } else {
        message.error(data.message);
      }
    })
  }

  @action generateRadioGroupConfig = (data) => {
    let tmp = this.toJS(this.showColumns);
    let config = [];
    data.showColumns && data.showColumns.length > 0 && config.push({
      label: getLabel('390081', '展示列'),
      labelcol: 3,
      fieldcol: 21,
      com: (
        <div>
            {
              data.showColumns.map((c, i) => {
                if(tmp[i] == null){
                  if(c.length > 1){
                    tmp[i] = c.reduce((pre, cur) => {
                      if(Array.isArray(pre)){
                        cur.selected && pre.push(cur.key);
                        return pre;
                      }else{
                        let arr = [];
                        pre.selected && arr.push(pre.key);
                        cur.selected && arr.push(cur.key);
                        return arr;
                      }
                    }).join(',');
                  }else{
                    c[0].selected && arr.push(c[0].key);
                  }
                  this.showColumns[i] = tmp[i];
                }
                return (
                  <div>
                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@ss3hj4@${i}`}
                      options={c}
                      detailtype='2'
                      value={this.showColumns[i]}
                      onChange={v => this.onSelectChange(v, i)}
                    />
                  </div>
                )
              })
            }
          </div>
      )
    });
    this.setDisplayColumns();
    config = config.concat(data.conditions);
    this.radioGroupConfig = config;
  }

  @action onSelectChange = (v, i) => {
    this.showColumns[i] = v;
    this.setDisplayColumns();
  }

  @action setDisplayColumns = () => {
    let arr = [];
    this.toJS(this.showColumns).map(g => arr = arr.concat(g.split(',')));
    let displayColumns = [];
    this.displayColumnsDef.map(cf => {
      const selected = (arr.indexOf(cf.key) > -1);
      displayColumns.push({
        key: cf.key,
        selected
      });
      cf.cascadekey != null && cf.cascadekey != '' && cf.cascadekey.split(',').map(k => {
        displayColumns.push({
          key: k,
          selected
        });
      })
    })
    this.displayColumns = displayColumns;
  }

  @action getTopProps = () => {
    let buttons = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ik1pqn`} op='setting' size="small" style={{ height: '28px' }} onClick={this.showAll} title={this.showHasNotAccount ? getLabel('31504','显示无账号人员') : getLabel('500013','不显示无账号人员')}>
        <span>
        {
            this.showHasNotAccount ?
            <i className='icon-coms-ShowNoAccount' style={{ color: '#2DB7F5' }} /> 
            : 
            <i className='icon-coms-NoAccountNoDisplay' style={{ color: '#8A8A8A' }} />
        }
        </span>
      </Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qgpksl`} type='primary' op='export' onClick={this.exportExcel}>{getLabel(28343, '导出Excel')}</Button>
    ];
    let menus = [];
    buttons.map((btn, index) => {
      const {
        props
      } = btn;
      let content;
      if (index == 0)
        content = props.title;
      menus.push({
        key: index.toString(),
        content: content || props.children,
        icon: <i className={this.menuIconCollection[props.op]}/>,
        onClick: props.onClick,
        disabled: props.disabled || false
      });
    })
    return {
      buttons,
      menus: [
        ...menus,
        // ...this.getBasicMenus("HRM_ENGINE_HRM_ANNUAL_MANAGER_SET")
      ]
    };
  };

  @action renderCol = column => {
    column.children && column.children.map(c => {
      const {
        title,
        unit,
        dataIndex,
        isdaily
      } = c;
      if (unit != null && unit != '') {
        c.title = (
          <div className='rSpan1' title={`${title}(${unit})`}>
            <div className='title'>{title}</div>
            <div className='unit'>({unit})</div>
          </div>
        )
      }
      c.render = (text, record, index) => {
        const params = this.getParams(c, record, isdaily);
        if (['signinstatus', 'signoutstatus'].some(v => dataIndex.indexOf(v) > -1)) {
          return <a onClick={() => this.showDetail(params,isdaily)} title={text}><div className='text-elli'><div dangerouslySetInnerHTML={{ __html: text }} /></div></a>;
        }
        return c.showDetial === '1' ? <a onClick={() => this.showDetail(params,isdaily)} title={text}><div className='text-elli'><div dangerouslySetInnerHTML={{ __html: text }} /></div></a> : <div dangerouslySetInnerHTML={{ __html: text }} />;
      }
      this.renderCol(c);
    })
  }

  @action convertColumns = (columns) => {
    columns.map((c, i) => {
      const {
        title,
        unit,
        isdaily
      } = c;
      if (unit != null && unit != '') {
        c.title = (
          <div className='rSpan2' title={`${title}(${unit})`}>
            <div className='title'>{title}</div>
            <div className='unit'>({unit})</div>
          </div>
        )
      }
      c.render = (text, record, index) => {
        let rs = text;
        if (c.dataIndex === 'kqdate') {
          const date = this.moment(text);
          if (date.isValid()) {
            const weekDay = date.day();
            rs = `${date.format('MM-DD')} ${this.weekdays[weekDay]}`;
            const holidayInfo = find(this.toJS(this.holidays), {
              date: date.format('YYYY-MM-DD')
            });
            return <div title={date.format('YYYY-MM-DD')} style={{ color: ((weekDay == 6 || weekDay == 0 || holidayInfo) ? "red" : "#000") }} title={rs}><div className='text-elli'>{rs}</div></div>
          }
        } else if (c.dataIndex == 'lastname') {
          return <a href={`javaScript:openhrm(${record.resourceId});`} onClick={e => window.pointerXY(e)} title={text}><div className='text-elli'>{text}</div></a>;
        } else if (c.dataIndex == 'subcompany') {
          return <a onClick={() => window.open(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${record.subcompanyId}`)} title={text}><div className='text-elli'>{text}</div></a>;
        } else if (c.dataIndex == 'department') {
          return <a onClick={() => window.open(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=department&id=${record.departmentId}`)} title={text}><div className='text-elli'>{text}</div></a>;
        } else if (c.dataIndex == 'jobtitle') {
          return <a onClick={() => window.open(`/spa/hrm/engine.html#/hrmengine/posts?id=${record.jobtitleId}`)} title={text}><div className='text-elli'>{text}</div></a>;
        } else if (c.dataIndex == 'workcode') {
          return <a href={`javaScript:openhrm(${record.resourceId});`} onClick={e => window.pointerXY(e)} title={text}><div className='text-elli'>{text}</div></a>;
        } else {
          const params = this.getParams(c, record, isdaily);
          return c.showDetial === '1' ? <a onClick={() => this.showDetail(params,isdaily)} title={text}><div className='text-elli'><div dangerouslySetInnerHTML={{ __html: text }} /></div></a> : <div dangerouslySetInnerHTML={{ __html: text }} />;
        }
      }
      this.renderCol(c);
    });

    return columns;
  }

  getParams = (column, record, isdaily) => {
    const {
      resourceId,
      kqdate
    } = record;

    const {
      dataIndex
    } = column;
    let params;

    if (isdaily === '1') {
      params = {
        resourceId,
        dataIndex: dataIndex,
        kqDate: kqdate
      }
    } else {
      params = {
        resourceId,
        typeselect: 6,
        viewScope: 0,
        fromDate: kqdate,
        toDate: kqdate,
        type: dataIndex,
        tabKey: 1,
      }
    }

    return params;
  }

  @action getKQReport = params => {
    if (this.spinning)
      return;
    this.spinning = true;
    api.getKQReport({
      data: JSON.stringify(params)
    }).then(data => {
      if (data.status === '1' || data.status == null) {
        this.holidays = data.holidays;
        this.table.columns = this.convertColumns(data.columns);
        this.table.datas = [...data.datas];
        this.pageIndex = data.pageindex;
        this.pageSize = data.pagesize || 10;
        this.total = data.count;
      } else {
        message.error(data.message);
      }
      this.spinning = false;
    }, error => this.spinning = false);
  }

  @action onRadioGroupChange = params => {
    this.radioGroupVal = params;
    if (params.typeselect === '6' && (params.fromDate === '' || params.toDate === ''))
      return;
    switch (params.viewScope) {
      case '1':
        if (params.subCompanyId == null || params.subCompanyId == '') {
          return;
        }
        break;
      case '2':
        if (params.departmentId == null || params.departmentId == '') {
          return;
        }
        break;
      case '3':
        if (params.resourceId == null || params.resourceId == '') {
          return;
        }
        break;
    }
    this.showHasNotAccount = ((['4', '5', '6', '7', '9'].indexOf(params.status || '')) > -1);
    this.getKQReport(this.getQueryParams(1));
  }

  @action showAll = () => {
    this.showHasNotAccount = !this.showHasNotAccount;
    this.getKQReport(this.getQueryParams());
  }

  @action exportExcel = () => {
    if (this.spinning)
      return;
    this.spinning = true;
    this.spinTip = getLabel('500702', '导出数据中，请稍候');
    const params = {
      ...this.getQueryParams(),
      showColumns: this.getShowColumns()
    };

    api.exportExcel({
      data: JSON.stringify(params)
    }).then(data => {
      this.spinning = false;
      this.spinTip = '';
      if (data.status === '1' && data.url != null && data.url.trim().length > 0)
        WeaTools.downloadFile(addContentPath(data.url), "GET");
    }, error => {
      this.spinning = false;
      this.spinTip = '';
    })
  }

  @observable detail = {
    userInfo: {},
    signInfo: '',
    columns: [],
    datas: [],
    tableStore: new TableStore,
    tabDatas:[],
    selectedKey:'',
  }



  @action showDetail = (params, isdaily) => {
    this.hasOnlyTable = (isdaily !== '1') ? true : false;

    if (isdaily === '1') {
      Object.assign(this.dialogParams.style, {
        width: 700,
        height: 452
      })
      api.getKQReportDetial(params).then(data => {
        if (data.status === '1') {
          const {
            userInfo,
            signInfo,
            table,
            dialogTitle
          } = data;

          Object.assign(this.detail.userInfo, userInfo);

          this.detail.signInfo = signInfo.signInfo;

          ['columns', 'datas'].map(v => {
            this.detail[v] = table[v];
          });

          this.dialogParams.title = dialogTitle;
          this.dialogParams.visible = true;
        } else {
          message.error(data.message);
        }
      }, error => {})
    } else {
      Object.assign(this.dialogParams.style, {
        width: 1000,
        height: 600
      })
      api.getTabs({type:params.type}).then(datas=>{
        const{tabs}=datas;

        this.detail.tabDatas = tabs;
        this.detail.selectedKey = (tabs.length>0)&& tabs.find( (tab,index)=>tab.selected || (tab.selected === undefined && index === 0)).key

        this.KQReportDetialProParams = params;
        this.getKQReportDetialPro();
      })
    }
  }

  getKQReportDetialPro=()=>{
    const params = this.KQReportDetialProParams;
    if (this.detail.selectedKey) {
      Object.assign(params, {
        tabKey: this.detail.selectedKey
      })
    }
    api.getKQReportDetialPro(params).then(data => {
          if (data.status === '1') {
            const {
              sessionkey,
              dialogTitle
            } = data;

            this.detail.tableStore.getDatas(sessionkey, 1);
            this.dialogParams.title = dialogTitle;
            this.dialogParams.visible = true;
          } else {
            message.error(data.message);
          }
        }, error => {})
  }

  handleDetailTabChange = (key)=>{
    this.detail.selectedKey = key;
    this.getKQReportDetialPro()
  }
  /********************* action list *********************/
}

export const hrmAttendanceDailyReport = new HrmAttendanceDailyReport();