import * as React from 'react'
import ShareBox from 'italent-share-box'
import CreateTask from 'italent-create-task'
import { TabBox } from '@beisen-cmps/italent-feedmix-components'
import { showSelectUser } from 'italent-user-select'
import XmlEntities from 'html-entities/lib/xml-entities.js'

import {
	getEmojiData,
	handleShareBoxSubmit,
	saveTaskFeed
} from '../../helper/require';

import {
	getApiUrl,
	imgPreview,
	getUserInfo,
	getMBlogFeedLocalStorage,
  setMBlogFeedLocalStorage,
  isOpenNewTaskApp,
  setUserLocalStorage,
  getUserLocalStorage,
} from '../../helper'
import { i18nDefaultInterface } from './iFeedInterface'

interface Props {
	handleAddFeed: (param: any) => void
	i18nTranslation: i18nDefaultInterface
}

interface States {
  isLoading: boolean,
  createTaskBoxKey?: number;
}

const CreateTaskStyle = {
  boxShadow: 'none',
  borderRadius: 3,
  boxSizing: 'border-box',
  width: '100%',
  height: 54
}



export default class FeedTab extends React.Component<Props, States> {
	shareBoxIns = null; // 分享框的实例
  shareBoxKey = 0; // 分享框的key
  isOpenNewTaskApp = false;
  createTaskBoxKey = 0;
  defaultData : any;
  selectTab = 0;
	static defaultProps = {
		i18nTranslation: {
			assignTaskText: '',
			shareText: ''
		}
	}
	constructor(props: Props) {
    super(props);
    this.isOpenNewTaskApp = isOpenNewTaskApp();
    this.selectTab = this.isOpenNewTaskApp ?  Number(getUserLocalStorage('activeTab')) : 0;


		this.state = {
			isLoading: false
		}
	}
	handleChange = (value: any) => {
    setUserLocalStorage('activeTab', value);
    this.selectTab = value;
    this.shareBoxKey += 1;
    this.setState({

    })
  }
  handleChangeTaskText =(value: string)=>{

    setUserLocalStorage('pc_feed_create_task_text', value);
  }
  handleChangeTaskDes=(value: string)=>{
    setUserLocalStorage('pc_feed_create_task_des', value);
  }
	// 获取回复框实例
	shareBoxRef = (node: any) => {
		this.shareBoxIns = node || null
	}
	// 提交发分享
	handleSubmit = (textValue: string, fileList: string[], scope: number) => {
		this.setState({
			isLoading: true
		})
		handleShareBoxSubmit(textValue, fileList, scope).then(data => {
			const { Code, Data } = data
			if (Code === 1) {
				this.props.handleAddFeed(Data)
				setMBlogFeedLocalStorage('', true)
				this.shareBoxKey += 1
				this.setState({
					isLoading: false
				})
			} else {
				this.setState({
					isLoading: false
				})
			}
		})
	}

	// 提交派任务
	handleSave = (data: any) => {
		const {
			title = '',
			chargeUser = 0,
			priority = [],
			date,
			des,
			partner,
			viewScope,
			relationData
		} = data
		const formatTitle = XmlEntities.encode(title)

		const { startTime, endTime } = date
		const selectedPriority = priority.find((item: any) => item.selected)
		const selectedPriorityValue = selectedPriority && selectedPriority.value
		const options = {
			TaskName: formatTitle,
			PrincipalUser: chargeUser,
			EndDate: endTime,
			StartDate: startTime,
			priority: selectedPriorityValue,
			Description: des, // 描述
			Participators: partner, // 参与人[]
			// FileUrls: this.filterArrayKey(files, 'DfsPath') || '', // 附件(暂时不支持，升级react16后放出)
			Visibility: viewScope.filter((v: any) => v.selected)[0].value, // 可见范围
			LabId: this.filterArrayKey(relationData, 'workId') || '' // 关联项目
		}
		saveTaskFeed(options).then((data: any) => {
			const { Code, OperationObject } = data
			// debugger;
			if (Code === 0) {
        setUserLocalStorage('pc_feed_create_task_text', '', true);
				setUserLocalStorage('pc_feed_create_task_des', '', true);
        this.props.handleAddFeed(OperationObject);
        const taskNewKey = this.createTaskBoxKey++;
        this.setState({
          createTaskBoxKey: taskNewKey,
        });
			}
		})
	}
	// 展示选人组件
	showSelectUserPop = (position: { top: number; left: number }) => {
		return showSelectUser({
			position: position,
			showMultipleBtn: true,
			sureEvent: this.insertToTextBox,
			offset: {
				left: -12,
				top: 18
			}
		})
	}
	// 插入选人结果到文本框
	insertToTextBox = (userList: any[]) => {
		if (!userList || !userList[0]) {
			return
		}
		var value = ''
		userList.forEach(function(user, index) {
			var Name = user.Name,
				Email = user.Email
			value += '@[' + Name + ':' + Email + '] '
		})
		value = value.slice(1)
		if (!!this.shareBoxIns) {
			const { handleInsert } = this.shareBoxIns as any
			handleInsert(value)
		}
	}
	filterArrayKey(arr: any, key: any) {
		let temp: any = []
		// eslint-disable-next-line
		arr &&
			arr.length > 0 &&
			arr.map((item: any) => {
				temp.push(item[key])
			})
		return temp.toString()
	}
	render() {
    const defaultData = {
      defaultTaskText: getUserLocalStorage('pc_feed_create_task_text'),
      defaultTaskDesc: getUserLocalStorage('pc_feed_create_task_des'),
    }
		const { IsUpaasManager = false, Role = 0 } = getUserInfo()
		//  超管 upaas管理员可以@全部同事
		const showAtAll = IsUpaasManager || Role === 2
		const { i18nTranslation } = this.props
		// 当前有部门的人员 才能选择仅部门可见
		const hasDepartment = !!getUserInfo().DepartmentId;

		const shareBoxProps = {
			textBoxOptions: {
				defaultValue: getMBlogFeedLocalStorage(),
				setStorage: setMBlogFeedLocalStorage
				// isShareBox: false
			},
			sureButton: {
				isLoading: this.state.isLoading,
				loadingText: i18nTranslation.shareLoadingText,
				handleClick: this.handleSubmit,
			},
			scopeOptions: {
				isShow: true,
				options: [
					{
						value: 0,
						text: i18nTranslation.allCanSeeText,
						isChecked: false,
						isDisabled: false
					},
					{
						value: 1,
						text: i18nTranslation.departmentVisibilityOnlytext,
						isChecked: false,
						isDisabled: !hasDepartment
					},
					{
						value: 2,
						text: i18nTranslation.someoneCanSeeText,
						isChecked: false,
						isDisabled: false
					}
				]
			},
			uploadOptions: {
				handlePreview: imgPreview,
				uploadUrl: getApiUrl('Upload/PostFiles?format=json')
			},
			atOptions: {},
			atAllOptions: {
				isShow: showAtAll
			},
			emojiOptions: {
				getData: getEmojiData,
				config: {}
			},
			isShareBox:  (getMBlogFeedLocalStorage() || '').trim().length === 0,
			showUserSelect: this.showSelectUserPop
		}

		const tabBoxProps = {
			options: [
        {
					value: 0,
					text: i18nTranslation.shareText,
					content: (
						<ShareBox
							{...shareBoxProps}
							ref={this.shareBoxRef}
							key={this.shareBoxKey}
						/>
					)
				},
			],
			handleChange: this.handleChange
    }
    if (this.isOpenNewTaskApp) {
      tabBoxProps.options.push({
        value: 1,
        text: i18nTranslation.assignTaskText,
        content: (
          <CreateTask

            outClass='tabBox-wrapper'
            useLine='#e6e8eb'
            defaultData={{
              title: defaultData.defaultTaskText,
              desc: defaultData.defaultTaskDesc
            }}
            handleSave={this.handleSave}
            styleWrap={CreateTaskStyle}
            key={this.createTaskBoxKey}
            onChangeDes={this.handleChangeTaskDes}
            onChangeText={this.handleChangeTaskText}
            placeholder={i18nTranslation.addTaskTips}
          />
        )
      });
    }
		return <TabBox {...tabBoxProps} defaultActiveValue={this.selectTab}/>
	}
}
