import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input,Select,Upload,Icon,Modal,Spin,message,Transfer } from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  initQueryFilter,
  getOnlyPropertyData,
  extendInclude, guid,setDataFieldValue
} from "../../../utils/common";
import DropDownPagination from '../../common/DropDownPaginationEx';
import EditComponent from "../../Lib/EditComponent";
import FormPage from '../../FormPage';
import config from "../../../config";
import moment from 'moment';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
class OG012EditPage extends EditComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {
      },
      level: '',
      fileEnable: true,
      investFileEnable: true
    };
  };
  
  onBeforeEdit(params){
    const {isNew,copySrcData,record}=params || {};
    const data = { ...this.state.data };
    const setFieldEditable = (field, editable) => { this.setFieldEditable(field, editable, this); };
    const setFieldVisible = (field, visible) => { this.setFieldVisible(field, visible, this) };

    const local_FileList=[];
    if(this.state.data && this.state.data.Nav_FileList){ 
      this.state.data.Nav_FileList.forEach(t=>{ 
        local_FileList.push({
            uid: t.ID,
            name: t.name?t.name:(t.Nav_File?t.Nav_File.FILE_NAME:'未知文件'),
            status: t.status?t.status:'done',
            response: {Data:t.FILE_ID,file:t},
          }); 
      });
    }
    
    const local_InvestigationFileList=[];
    if(this.state.data&&this.state.data.Nav_InvestigationFileList){ 
      this.state.data.Nav_InvestigationFileList.forEach(t=>{ 
        local_InvestigationFileList.push({
            uid: t.ID,
            name: t.name?t.name:(t.Nav_File?t.Nav_File.FILE_NAME:'未知文件'),
            status: t.status?t.status:'done',
            response: {Data:t.FILE_ID,file:t},
          }); 
      });
    }
    let s = 0;
    if (!isNew && data && data.STATUS !== undefined){
      s = data.STATUS;
    }
    setFieldVisible("START_TIME"                   , s >= 0);
    setFieldVisible("Nav_User.NAME"                , s >= 0);
    setFieldVisible("Nav_LaunchDepartment.NAME"    , s >= 0);
    setFieldVisible("NAME"                         , s >= 0);
    setFieldVisible("Nav_ItemEnum.NAME"            , s >= 0);
    setFieldVisible("DESCRIPTION"                  , s >= 0);
    setFieldVisible("Nav_FileList.Nav_File.NAME"   , s >= 0);
    setFieldVisible("Nav_Assignee.NAME"            , s >= 1);
    setFieldVisible("ASSIGNEE_STATUS"              , s >= 1);
    setFieldVisible("ASSIGNEE_DESCRIPTION"         , s >= 1);
    setFieldVisible("Nav_ImplementDepartment.NAME"        , s >= 1);
    setFieldVisible("Nav_ImplementUser.NAME"              , s >= 1);
    setFieldVisible("IMPLEMENT_DESCRIPTION"        , s >= 2);
    setFieldVisible("Nav_InvestigationFileList.Nav_File.NAME", s >= 2);
    setFieldVisible("SATISFACTION_STATUS"          , s >= 3);

 

    let curUid = this.props.login.user.ID;
    let launchUid = data && data.USER_ID ?  data.USER_ID : null;
    let acceptUid = data && data.ASSIGNEE_ID ?  data.ASSIGNEE_ID : null;
    let doUid = data && data.IMPLEMENT_USER_ID ?  data.IMPLEMENT_USER_ID : null;

    this.state.fileEnable = s == 0 && (!launchUid || curUid === launchUid)
    this.state.investFileEnable = s === 2 && (curUid === doUid)

    setFieldEditable("START_TIME"                   , false);
    setFieldEditable("Nav_User.NAME"                , false);
    setFieldEditable("Nav_LaunchDepartment.NAME"    , false);
    setFieldEditable("NAME"                         , s == 0 && (!launchUid || curUid === launchUid));
    setFieldEditable("Nav_ItemEnum.NAME"            , s == 0 && (!launchUid || curUid === launchUid));
    setFieldEditable("DESCRIPTION"                  , s == 0 && (!launchUid || curUid === launchUid));
    setFieldEditable("Nav_FileList.Nav_File.NAME"   , this.state.fileEnable);
    setFieldEditable("Nav_Assignee.NAME"            , false);
    setFieldEditable("ASSIGNEE_STATUS"              , s === 1 && (curUid === acceptUid));
    setFieldEditable("ASSIGNEE_DESCRIPTION"         , s === 1 && (curUid === acceptUid));
    setFieldEditable("Nav_ImplementDepartment.NAME"        , s === 1 && (curUid === acceptUid));
    setFieldEditable("Nav_ImplementUser.NAME"              , s === 1 && (curUid === acceptUid));
    setFieldEditable("IMPLEMENT_DESCRIPTION"        , s === 2 && (curUid === doUid));
    setFieldEditable("Nav_InvestigationFileList.Nav_File.NAME", this.state.investFileEnable);
    setFieldEditable("SATISFACTION_STATUS"          , s === 3 && (curUid === launchUid));





    this.setState({
      local_FileList,
      local_InvestigationFileList,
      data
    })
  }
  doSaveFile(record,srcRecord,recordFiledName,stateFiledName){
    if(!record[recordFiledName]){
        record[recordFiledName]=[];
    }
    if(srcRecord[recordFiledName]){
        srcRecord[recordFiledName].forEach(t=>{
        record[recordFiledName].push(getOnlyPropertyData(t));
        })
    }
    if(this.state[stateFiledName]) {
        this.state[stateFiledName].forEach(t => {
        if (t.response) {
            if (record[recordFiledName].filter(t1 => t1.FILE_ID === t.response.Data).length == 0) {
            record[recordFiledName].push({
                ID: guid(),
                FILE_ID: t.response.Data,
                ORG_ID: this.props.login.OrgId,
                name: t.name,
                status: t.status,
            });
            }
        }
        });
    }
    if (record[recordFiledName]) {
        record[recordFiledName].forEach(t1 => {
          if (!this.state[stateFiledName] || this.state[stateFiledName].filter(t => t.response && t1.FILE_ID === t.response.Data).length == 0) {
              t1.IS_DELETED = true;
          }
        });
    }
  }
  onBeforeSaveHandleRecord(params){
    super.onBeforeSaveHandleRecord(params);
    const {editCode,record,srcRecord}=params?params:{};
    this.doSaveFile(record,srcRecord,'Nav_FileList','local_FileList');
    if(this.state.data.STATUS == 2){
      this.doSaveFile(record,srcRecord,'Nav_InvestigationFileList','local_InvestigationFileList');
    }
  }


  handleSopShowModal = (file) => {
    var urls = config.serviceHost + 'PF/File/GetFile?id=' + file.response.Data;
    fetch(urls).then(res => res.blob()).then(blob => {
        const a = document.createElement('a');
        document.body.appendChild(a)
        a.style.display = 'none'
        // 使用获取到的blob对象创建的url
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        // 指定下载的文件名
        a.download = file.name;
        a.click();
        document.body.removeChild(a)
        // 移除blob对象的url
        window.URL.revokeObjectURL(url);
    }, () => {
    
    });
  };
  onRenderHeadControl(params){
    const {colConfig,record}=params;
    switch (colConfig.field){
      case 'Nav_FileList.Nav_File.NAME':{
        const props = {
          name: 'file',
          disabled: colConfig.disabled,
          action: config.serviceHost +'PF/File/UploadFile',
          data:{OrgId:this.props.login.OrgId},
          fileList:this.state.local_FileList,
          onPreview: (file) =>{
            this.handleSopShowModal(file);
          },
          onRemove: (file) =>{
            if(!this.state.fileEnable){
              return false
            }
          },
          onChange:(info)=>{
            this.setState({
              local_FileList:info.fileList,
            });
            if (info.file.status === 'done') {
              message.success(`${info.file.name} 上传成功`);
            } else if (info.file.status === 'error') {
              message.error(`${info.file.name} 上传失败`);
            }
          },
        };
        return <>
          <Upload {...props}>
            <Button  disabled={!this.state.fileEnable}>
              <Icon type="upload" /> 上传附件
            </Button>
          </Upload>
        </>
      }
      case 'Nav_InvestigationFileList.Nav_File.NAME':{
        const props = {
          name: 'file',
          action: config.serviceHost +'PF/File/UploadFile',
          data:{OrgId:this.props.login.OrgId},
          fileList:this.state.local_InvestigationFileList,
          onPreview: (file) =>{
            this.handleSopShowModal(file);
          },
          onRemove: (file) =>{
            if(!this.state.investFileEnable){
              return false
            }
          },
          onChange:(info)=>{
            this.setState({
              local_InvestigationFileList:info.fileList,
            });
            if (info.file.status === 'done') {
              message.success(`${info.file.name} 上传成功`);
            } else if (info.file.status === 'error') {
              message.error(`${info.file.name} 上传失败`);
            }
          },
        };
        return <>
          <Upload {...props}>
            <Button  disabled={!this.state.investFileEnable}>
              <Icon type="upload" /> 上传附件
            </Button>
          </Upload>
        </>
      }
      default:{
        return super.onRenderHeadControl(params);
        break;
      }
    }
  }
  

}


export default connect(({ login, loading,custom,app }) => ({ login, loading,custom,app}))(Form.create()(OG012EditPage));
