import OutSidePanel from "@/component/layout/outsidepanel"
import { httpUtil } from "@/utils"
import { Descriptions, Spin, Tag,Table,Tooltip,Typography,Space,Button,Divider,Modal,Form,Input,Timeline } from "antd"
import React,{useMemo,useState,useEffect} from "react"
import { useGetFlowAction, useGetProcessDetail } from "../hooks"
import moment from "moment"
import config from "@/commons"
import { useGetModalInfoAndAction } from "@/hooks/common"
import produce from 'immer'
import { AuditUsersItem } from "../../AssetDraft/start-flow"
import {showMessage} from "@/util"

const {api:{asset}} =config

const FlowAcceptDetail:React.FC<any>=(props)=>{

    const {location} = props

    const [dataSource,setDataSource] = useState([])
    const [form] = Form.useForm()

    const {loading,saveQuestionItemFinal,saveQuestionItemNext} = useGetFlowAction()

    const processId:string = useMemo(()=>{
        return httpUtil.getQueryVariable('processId',location.search)||''
    },[location.search])

    const {detail,detalLoading,reload} = useGetProcessDetail({processId})
    const editmodal = useGetModalInfoAndAction()

    useEffect(()=>{
        if(detail?.submitItems){
            setDataSource(detail.submitItems)
        }
    },[detail])

    const openDetail=(id)=>{
        window.open(`${asset}/fileApi/downloadFile?fileId=${id}`)
    }

    const openEdit=(record:any)=>{
        const list = Object.values(record.responsibilityAttributeMap);
        editmodal.openModal({listinfo:list},{item:record})
    }

    const save=(values)=>{
        const map = {};
        const data = editmodal.item;
        const list = Object.values(data.responsibilityAttributeMap);
        list.forEach((item:any)=>{
            map[item.enName] = {...item,value:values[item.enName]}
        })
        setDataSource(prev => {
            return produce(prev, (draft) => {
              const index = dataSource.findIndex((item)=>(item.dataAssetId===data.dataAssetId))
              draft[index].responsibilityAttributeMap = map
            })
        })
        editmodal.cancelModal()
    }

    const cols = [
        {
          title: '序号',
          dataIndex: 'index',
          width:60,
          render:(_, __, index)=> (index+1)
        },
        {
          title: '资产名称',
          dataIndex: 'enName',
          width: 160,
          render: (text, record) => (
            <Tooltip title={text}>
              <Typography.Text ellipsis={true}>
                {text}
              </Typography.Text>
            </Tooltip>
          )
        },
        {
          title: '中文名称',
          dataIndex: 'cnName',
          width: 160,
          render: (text, record) => (
            <Tooltip title={text}>
              <Typography.Text ellipsis={true}>
                {text}
              </Typography.Text>
            </Tooltip>
          )
        },
        {
          title: '编码',
          dataIndex: 'code',
          width: 160,
          render: (text, record) => (
            <Tooltip title={text}>
              <Typography.Text ellipsis={true}>
                {text}
              </Typography.Text>
            </Tooltip>
          )
        },
        {
          title: '路径',
          dataIndex: 'path',
          width: 120,
          render: (text, record) => (
            <Tooltip title={text}>
              <Typography.Text ellipsis={true}>
                {text}
              </Typography.Text>
            </Tooltip>
          )
        },
        {
          title: '待完成属性',
          key: 'columns',
          dataIndex:'responsibilityAttributeMap',
          render: (text, record) => {
            const name = Object.values((text||{})).map((item:any)=>{
              return `${item.cnName}:${item?.value}`
            })
            
            return (
              <Tooltip title={name.join(',')}>
                <Typography.Text ellipsis={true}>
                  {name.join(',')}
                </Typography.Text>
              </Tooltip>
            )
          }
        },
        {
            title: '操作',
            key: 'aciton',
            render: (text, record) => {
              return (
                <Space>
                    <Button type='link' size='small' style={{ padding: 0 }} onClick={()=>{openEdit(record)}}>编辑</Button>
                    {/* <Divider type='vertical' style={{margin:0}} />
                    <Button type='link' size='small' disabled={support} style={{ padding: 0 }} onClick={()=>{dosupport(record,false)}}>反对</Button> */}
                </Space>
              )
            }
        },
    ]

    const nextUser=()=>{
      form.validateFields().then((data)=>{
        if(data?.nextAuditUsers&&data?.nextAuditUsers.length){
          const playload = {...detail,...data,submitItems:dataSource}
          saveQuestionItemNext(playload,()=>{
            showMessage('success','操作成功')
            reload?.()
          })
        }else{
          showMessage('info','请选择下一步处理人')
        }
      })
    }

    const finishFlow=()=>{
      form.validateFields().then((data)=>{
        if((data?.nextAuditUsers||[]).length===0){
          let allow = true;
          const list = dataSource.map((item)=>{
            Object.values(item.responsibilityAttributeMap).forEach((i:any)=>{
              if(!i.value){
                allow=false
              }
            })
            return {...item,auditStatus:1}
          })
          if(allow){
            const playload = {...detail,...data,submitItems:list}
            saveQuestionItemFinal(playload,()=>{
              showMessage("success",'操作成功')
              reload?.()
            })
          }else{
            showMessage('info','请完成待完成项')
          }
          
        }else{
          showMessage('info',"结束流程不需要下一步处理人")
        }
      })
    }

    return(
        <OutSidePanel 
            title="资产认责审批"
            body={
                <React.Fragment>
                    <Spin spinning={detalLoading}>
                        <h2 style={{marginRight:12}}>基本信息</h2>
                        <Descriptions>
                            <Descriptions.Item label="创建人">
                                {`${detail?.applyUser?.userName}(${detail?.applyUser?.userDisplayName})`}
                            </Descriptions.Item>
                            <Descriptions.Item label="创建时间">
                                {detail?.createTimestamp&&moment(detail.createTimestamp).format("YYYY-MM-DD HH:mm:ss")}
                            </Descriptions.Item>
                            <Descriptions.Item label="附件">
                                {
                                    (detail?.attachments||[]).map((item:any,key:number)=>{
                                        return <Tag color="blue" key={key} style={{cursor:'pointer'}} onClick={()=>{openDetail(item.fileId)}} >{item?.fileName}</Tag>
                                    })
                                }
                            </Descriptions.Item>
                        </Descriptions>
                        <h2 style={{marginRight:12,marginTop:10}}>问责数据</h2>
                        <Table
                            columns={cols??[]}
                            dataSource={dataSource??[]}
                            pagination={false}
                            rowKey="dataAssetId"
                        />
                        <h2 style={{marginRight:12,marginTop:20,marginBottom:20}}>审批意见列表</h2>
                        <Timeline>
                            {
                                (detail?.processInfos||[]).map((item:any,key:number)=>{
                                    return(
                                        <Timeline.Item key={key}>
                                            <p>{`${item.userName}(${item.userDisplayName})`}<span style={{marginLeft:10}}>{item.auditTimestamp&&moment(item.auditTimestamp).format("YYYY-MM-DD HH:mm:ss")}</span></p>
                                            <p>审批意见：{item.opinion}</p>
                                        </Timeline.Item>
                                    )
                                })
                            }
                            
                        </Timeline>
                        <h2 style={{marginRight:12,marginTop:20,marginBottom:20}}>我的答复</h2>
                        <Form form={form} layout="vertical">
                          <Form.Item
                            label='答复内容'
                            name="opinion"
                            rules={[{ required: true, message: '必填项!' }]}
                          >
                            <Input.TextArea 
                              placeholder="请输入审批已经"
                              autoSize={{minRows:3,maxRows:6}}
                            />
                          </Form.Item>
                          <Form.Item
                            label='下一步处理人'
                            name="nextAuditUsers"
                            style={{ marginBottom:15 }}
                            rules={[{ required: false, message: '请选择评审人员!' }]}
                          >
                            <AuditUsersItem  />
                          </Form.Item>
                        </Form>
                    </Spin>
                    <DynamicFormModal visible={editmodal.visible} onSubmit={save} onCancel={()=>{editmodal.cancelModal()}} list={editmodal.currentItem} />
                </React.Fragment>
            }
            footer={
              <div style={{display:'flex',justifyContent:'center',width:'100%'}}>
                <Space>
                  <Button loading={loading} disabled={!detail?.operateAble} onClick={nextUser} type="primary">转分配</Button>
                  <Button loading={loading} disabled={!detail?.operateAble} onClick={finishFlow} type="primary">保存</Button>
                </Space>
              </div>
            }
        />
    )
}

export default FlowAcceptDetail

const DynamicFormModal: React.FC<{ visible: boolean; list: any; onCancel: () => void; onSubmit: (values: any) => void }> = ({
  visible,
  list,
  onCancel,
  onSubmit,
}) => {
  const [form] = Form.useForm();

  const {listinfo} = list

  return (
    <Modal
      visible={visible}
      title="补全信息"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            onSubmit(values);
            form.resetFields();
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form form={form} layout="vertical">
        {(listinfo||[]).map((item) => (
          <Form.Item
            key={item.enName}
            name={item.enName}
            label={item.cnName}
            rules={[{ required: true, message: '必填项!' }]}
          >
            {item.component || <Input />}
          </Form.Item>
        ))}
      </Form>
    </Modal>
  );
};