(function(d,o){typeof exports=="object"&&typeof module!="undefined"?o(exports,require("@tachybase/client"),require("react/jsx-runtime"),require("react"),require("react-dom"),require("@ant-design/icons"),require("antd"),require("react-i18next"),require("@tachybase/schema"),require("lodash"),require("@tego/client")):typeof define=="function"&&define.amd?define(["exports","@tachybase/client","react/jsx-runtime","react","react-dom","@ant-design/icons","antd","react-i18next","@tachybase/schema","lodash","@tego/client"],o):(d=typeof globalThis!="undefined"?globalThis:d||self,o(d["@tachybase/plugin-action-import"]={},d["@tachybase/client"],d.jsxRuntime,d.react,d["react-dom"],d["@ant-design/icons"],d.antd,d["react-i18next"],d["@tachybase/schema"],d.lodash,d["@tego/client"]))})(this,function(d,o,m,w,L,_,T,C,g,O,X){"use strict";var be=Object.defineProperty,Ae=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var me=Object.getOwnPropertySymbols;var Ce=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable;var ue=(d,o,m)=>o in d?be(d,o,{enumerable:!0,configurable:!0,writable:!0,value:m}):d[o]=m,B=(d,o)=>{for(var m in o||(o={}))Ce.call(o,m)&&ue(d,m,o[m]);if(me)for(var m of me(o))Te.call(o,m)&&ue(d,m,o[m]);return d},H=(d,o)=>Ae(d,we(o));var R=(d,o,m)=>new Promise((w,L)=>{var _=g=>{try{C(m.next(g))}catch(O){L(O)}},T=g=>{try{C(m.throw(g))}catch(O){L(O)}},C=g=>g.done?w(g.value):Promise.resolve(g.value).then(_,T);C((m=m.apply(d,o)).next())});const V=w.createContext(null);V.displayName="ImportContext";const G=()=>w.useContext(V);var k=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},q={exports:{}},xe=q.exports,J;function he(){return J||(J=1,function(t,e){(function(c,n){n()})(xe,function(){function c(s,p){return typeof p=="undefined"?p={autoBom:!1}:typeof p!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),p={autoBom:!p}),p.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(s.type)?new Blob(["\uFEFF",s],{type:s.type}):s}function n(s,p,f){var a=new XMLHttpRequest;a.open("GET",s),a.responseType="blob",a.onload=function(){h(a.response,p,f)},a.onerror=function(){console.error("could not download file")},a.send()}function u(s){var p=new XMLHttpRequest;p.open("HEAD",s,!1);try{p.send()}catch(f){}return 200<=p.status&&299>=p.status}function i(s){try{s.dispatchEvent(new MouseEvent("click"))}catch(f){var p=document.createEvent("MouseEvents");p.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),s.dispatchEvent(p)}}var r=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof k=="object"&&k.global===k?k:void 0,l=r.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),h=r.saveAs||(typeof window!="object"||window!==r?function(){}:"download"in HTMLAnchorElement.prototype&&!l?function(s,p,f){var a=r.URL||r.webkitURL,x=document.createElement("a");p=p||s.name||"download",x.download=p,x.rel="noopener",typeof s=="string"?(x.href=s,x.origin===location.origin?i(x):u(x.href)?n(s,p,f):i(x,x.target="_blank")):(x.href=a.createObjectURL(s),setTimeout(function(){a.revokeObjectURL(x.href)},4e4),setTimeout(function(){i(x)},0))}:"msSaveOrOpenBlob"in navigator?function(s,p,f){if(p=p||s.name||"download",typeof s!="string")navigator.msSaveOrOpenBlob(c(s,f),p);else if(u(s))n(s,p,f);else{var a=document.createElement("a");a.href=s,a.target="_blank",setTimeout(function(){i(a)})}}:function(s,p,f,a){if(a=a||open("","_blank"),a&&(a.document.title=a.document.body.innerText="downloading..."),typeof s=="string")return n(s,p,f);var x=s.type==="application/octet-stream",v=/constructor/i.test(r.HTMLElement)||r.safari,S=/CriOS\/[\d]+/.test(navigator.userAgent);if((S||x&&v||l)&&typeof FileReader!="undefined"){var b=new FileReader;b.onloadend=function(){var y=b.result;y=S?y:y.replace(/^data:[^;]*;/,"data:attachment/file;"),a?a.location.href=y:location=y,a=null},b.readAsDataURL(s)}else{var F=r.URL||r.webkitURL,E=F.createObjectURL(s);a?a.location=E:location.href=E,a=null,setTimeout(function(){F.revokeObjectURL(E)},4e4)}});r.saveAs=h.saveAs=h,t.exports=h})}(q)),q.exports}var W=he();const I="action-import",$={IMPORTING:1,IMPORTED:2},fe=t=>{const{t:e}=C.useTranslation(I),{importModalVisible:c,importStatus:n,importResult:u,setImportModalVisible:i}=G(),{data:r,meta:l}=u!=null?u:{},h=()=>{i(!1)},s=()=>{const p=new Int8Array(r==null?void 0:r.data),f=new Blob([p],{type:"application/x-xls"});W.saveAs(f,"fail.xlsx")};return m.jsx(T.Modal,{title:e("Import Data"),width:"50%",styles:{body:{height:"calc(80vh - 200px)"}},open:c,footer:null,closable:n===$.IMPORTED,onCancel:h,children:m.jsxs("div",{className:o.css`
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100%;
        `,children:[n===$.IMPORTING&&m.jsx(T.Spin,{indicator:m.jsx(_.LoadingOutlined,{style:{fontSize:24},spin:!0}),tip:e("Excel data importing")}),n===$.IMPORTED&&m.jsxs(T.Space,{direction:"vertical",align:"center",children:[m.jsx(_.ExclamationCircleFilled,{style:{fontSize:72,color:"#1890ff"}}),m.jsx("p",{children:e("Import done, total success have {{successCount}} , total failure have {{failureCount}}",B({},l!=null?l:{}))}),m.jsxs(T.Space,{children:[(l==null?void 0:l.failureCount)>0&&m.jsx(T.Button,{onClick:s,children:e("To download the failure data")}),m.jsx(T.Button,{type:"primary",onClick:h,children:e("Done")})]})]})]})})},K=t=>{let e=t;for(;e&&e["x-action"]!=="importXlsx";)e=e.parent;return{schema:e}},Y=t=>!t||!Array.isArray(t)?[]:t,Q=()=>{const{service:t,resource:e}=o.useBlockRequestContext();o.useAPIClient();const c=g.useFieldSchema(),n=o.useCompile(),{getCollectionJoinField:u,getCollectionField:i}=o.useCollectionManager_deprecated(),{name:r,title:l,getField:h}=o.useCollection_deprecated(),{t:s}=C.useTranslation(I),{schema:p}=K(c);return{run(){return R(this,null,function*(){var F,E;const{importColumns:a,explain:x}=O.cloneDeep((E=(F=p==null?void 0:p["x-action-settings"])==null?void 0:F.importSettings)!=null?E:{}),v=Y(a).map(y=>{var D,N;const M=i(`${r}.${y.dataIndex[0]}`);if(M){if(y.defaultTitle=n((D=M==null?void 0:M.uiSchema)==null?void 0:D.title)||M.name,y.dataIndex.length>1){const P=u(`${r}.${y.dataIndex.join(".")}`);if(!P)return;y.defaultTitle=y.defaultTitle+"/"+n((N=P==null?void 0:P.uiSchema)==null?void 0:N.title)||P.name}return M.interface==="chinaRegion"&&y.dataIndex.push("name"),y}}).filter(Boolean),{data:S}=yield e.downloadXlsxTemplate({values:{title:n(l),explain:x,columns:n(v)}},{method:"post",responseType:"blob"}),b=new Blob([S],{type:"application/x-xls"});W.saveAs(b,`${n(l)}.xlsx`)})}}},Z=()=>{const{service:t,resource:e}=o.useBlockRequestContext(),c=o.useAPIClient(),n=g.useFieldSchema(),u=o.useCompile(),{getCollectionJoinField:i,getCollectionField:r}=o.useCollectionManager_deprecated(),{name:l,title:h,getField:s}=o.useCollection_deprecated(),{t:p}=C.useTranslation(I),{schema:f}=K(n),a=g.useForm(),{setVisible:x}=o.useActionContext(),{setImportModalVisible:v,setImportStatus:S,setImportResult:b}=G();return{run(){return R(this,null,function*(){var P,ce,pe;const{importColumns:E,explain:y}=O.cloneDeep((ce=(P=f==null?void 0:f["x-action-settings"])==null?void 0:P.importSettings)!=null?ce:{}),M=Y(E).map(A=>{var le,de;const j=r(`${l}.${A.dataIndex[0]}`);if(j){if(A.defaultTitle=u((le=j==null?void 0:j.uiSchema)==null?void 0:le.title)||j.name,A.dataIndex.length>1){const U=i(`${l}.${A.dataIndex.join(".")}`);if(!U)return;A.defaultTitle=A.defaultTitle+"/"+u((de=U==null?void 0:U.uiSchema)==null?void 0:de.title)||U.name}return j.interface==="chinaRegion"&&A.dataIndex.push("name"),A}}).filter(Boolean),D=new FormData,N=a.values.upload.map(A=>A.originFileObj);D.append("file",N[0]),D.append("columns",JSON.stringify(M)),D.append("explain",y),x(!1),v(!0),S($.IMPORTING);try{const{data:A}=yield c.axios.post(`${l}:importXlsx`,D,{timeout:6e5});b(A),a.reset(),yield(pe=t==null?void 0:t.refresh)==null?void 0:pe.call(t),S($.IMPORTED)}catch(A){v(!1),x(!0)}})}}},ge=["id","createdAt","createdBy","updatedAt","updatedBy"],ee=t=>{const{getCollectionFields:e}=o.useCollectionManager_deprecated(),c=e(t),n=(i,r)=>{var h;if(!i.interface||ge.includes(i.interface))return;const l={name:i.name,title:((h=i==null?void 0:i.uiSchema)==null?void 0:h.title)||i.name,schema:i==null?void 0:i.uiSchema};if(!i.target||r>=2)return l;if(i.target){const s=e(i.target),p=u(s,r+1).filter(Boolean);l.children=l.children||[],l.children.push(...p)}return l},u=(i,r)=>{const l=[];return i.forEach(h=>{const s=n(h,r);s&&l.push(s)}),l};return u(c,1)},ve=["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel"],z=()=>{const{t}=C.useTranslation(I),{name:e}=o.useCollection_deprecated(),c=ee(e);return{importSettingsSchema:{type:"void","x-component":"Grid",properties:{explain:{type:"string",title:`{{ t("Import explain", {ns: "${I}"}) }}`,"x-decorator":"FormItem","x-component":"Input.TextArea"},importColumns:{type:"array","x-component":"ArrayItems","x-decorator":"FormItem",items:{type:"object",properties:{space:{type:"void","x-component":"Space","x-component-props":{className:o.css`
                    width: 100%;
                    & .ant-space-item:nth-child(2) {
                      flex: 1;
                    }
                  `},properties:{sort:{type:"void","x-decorator":"FormItem","x-component":"ArrayItems.SortHandle"},dataIndex:{type:"array","x-decorator":"FormItem","x-component":o.Cascader,required:!0,enum:c,"x-component-props":{fieldNames:{label:"title",value:"name",children:"children"},changeOnSelect:!1}},remove:{type:"void","x-decorator":"FormItem","x-component":"ArrayItems.Remove"}}}}},properties:{add:{type:"void",title:`{{ t("Add importable field", {ns: "${I}"}) }}`,"x-component":"ArrayItems.Addition","x-component-props":{className:o.css`
                  border-color: var(--colorSettings);
                  color: var(--colorSettings);
                  &.ant-btn-dashed:hover {
                    border-color: var(--colorSettings);
                    color: var(--colorSettings);
                  }
                `}}}}}},beforeUploadHandler(){return!1},uploadValidator(n,u){var r;if(n.length>1)return{type:"error",message:t("Only one file is allowed to be uploaded")};const i=(r=n[0])!=null?r:{};return i.size>10*1024*1024?{type:"error",message:t("File size cannot exceed 10M")}:ve.includes(i.type)?"":{type:"error",message:t("Please upload the file of Excel")}},validateUpload(n,u,i){var l;const[r]=i;u.disabled=(r==null?void 0:r.length)===0,u.componentProps=H(B({},u.componentProps),{disabled:(r==null?void 0:r.length)===0||((l=n.errors)==null?void 0:l.length)>0})}}},te=t=>{const{uploadValidator:e,beforeUploadHandler:c,validateUpload:n}=z();return m.jsx(o.SchemaComponentOptions,{components:{ImportActionInitializer:ae,ImportDesigner:se},scope:{uploadValidator:e,validateUpload:n,beforeUploadHandler:c,useDownloadXlsxTemplateAction:Q,useImportStartAction:Z},children:m.jsx(oe,{children:t.children})})},oe=t=>{const[e,c]=w.useState(!1),[n,u]=w.useState($.IMPORTING),[i,r]=w.useState(null);return m.jsxs(V.Provider,{value:{importModalVisible:e,setImportModalVisible:c,importStatus:n,setImportStatus:u,importResult:i,setImportResult:r},children:[L.createPortal(m.jsx(fe,{}),document.body),t.children]})},ye=new o.SchemaSettings({name:"actionSettings:import",items:[{name:"editButton",Component:o.ButtonEditor,useComponentProps(){const{buttonEditorProps:t}=o.useSchemaToolbar();return t}},{name:"importableFields",type:"actionModal",useComponentProps(){var l,h;const t=g.useField(),e=g.useFieldSchema(),{t:c}=C.useTranslation(),{dn:n}=o.useDesignable(),[u,i]=w.useState(),{importSettingsSchema:r}=z();return w.useEffect(()=>{i(r)},[t.address,(l=e==null?void 0:e["x-action-settings"])==null?void 0:l.importSettings]),{title:c("Importable fields"),schema:u,initialValues:B({},(h=e==null?void 0:e["x-action-settings"])==null?void 0:h.importSettings),components:{ArrayItems:X.ArrayItems},onSubmit:({importColumns:s,explain:p})=>{const f=s==null?void 0:s.filter(a=>{var x;return(x=a==null?void 0:a.dataIndex)==null?void 0:x.length}).map(a=>({dataIndex:a.dataIndex.map(x=>{var v;return(v=x.name)!=null?v:x}),title:a.title}));e["x-action-settings"].importSettings={importColumns:f,explain:p},n.emit("patch",{schema:{"x-uid":e["x-uid"],"x-action-settings":e["x-action-settings"]}}),n.refresh()}}}},{name:"divider",type:"divider"},{name:"delete",type:"remove",useComponentProps(){const{t}=C.useTranslation();return{removeParentsIfNoChildren:!0,breakRemoveOn:e=>e["x-component"]==="Space"||e["x-component"].endsWith("ActionBar"),confirm:{title:t("Delete action")}}}}]}),ne=(t,e,c)=>t.reduceProperties((n,u)=>{if(u[e]===c)return u;const i=ne(u,e,c);return i||n}),Se=(t,e)=>e(t),re=(t,e,c=ne,n=Se)=>{const u=g.useFieldSchema(),{remove:i}=o.useDesignable(),r=c(u,e,t);return{schema:r,exists:!!r,remove(){r&&n(r,i)}}},Ie=t=>({importColumns:t==null?void 0:t.filter(c=>!c.children).map(c=>({dataIndex:[c.name]})),explain:""}),ae=()=>{const t=o.useSchemaInitializerItem(),{insert:e}=o.useSchemaInitializer(),{exists:c,remove:n}=re("importXlsx","x-action",t.find,t.remove),{name:u}=o.useCollection_deprecated(),i=ee(u),r={type:"void",title:'{{ t("Import") }}',"x-action":"importXlsx","x-action-settings":{importSettings:{importColumns:[],explain:""}},"x-toolbar":"ActionSchemaToolbar","x-settings":"actionSettings:import","x-component":"Action","x-component-props":{icon:"CloudUploadOutlined",openMode:"modal"},properties:{modal:{type:"void",title:`{{ t("Import Data", {ns: "${I}" }) }}`,"x-component":"Action.Container","x-decorator":"Form","x-component-props":{width:"50%",className:o.css`
            .ant-formily-item-label {
              height: var(--controlHeightLG);
            }
          `},properties:{formLayout:{type:"void","x-component":"FormLayout",properties:{download:{type:"void",title:`{{ t("Step 1: Download template", {ns: "${I}" }) }}`,"x-component":"FormItem","x-acl-ignore":!0,properties:{tip:{type:"void","x-component":"Markdown.Void","x-editable":!1,"x-component-props":{style:{padding:"var(--paddingContentVerticalSM)",backgroundColor:"var(--colorInfoBg)",border:"1px solid var(--colorInfoBorder)",color:"var(--colorText)",marginBottom:"var(--marginSM)"},content:`{{ t("Download tip", {ns: "${I}" }) }}`}},downloadAction:{type:"void",title:`{{ t("Download template", {ns: "${I}" }) }}`,"x-component":"Action","x-component-props":{className:o.css`
                        margin-top: 5px;
                      `,useAction:"{{ useDownloadXlsxTemplateAction }}"}}}},upload:{type:"array",title:`{{ t("Step 2: Upload Excel", {ns: "${I}" }) }}`,"x-decorator":"FormItem","x-acl-ignore":!0,"x-component":"Upload.Dragger","x-validator":"{{ uploadValidator }}","x-component-props":{action:"",height:"150px",tipContent:`{{ t("Upload placeholder", {ns: "${I}" }) }}`,beforeUpload:"{{ beforeUploadHandler }}"}}}},footer:{"x-component":"Action.Container.Footer","x-component-props":{},properties:{actions:{type:"void","x-component":"ActionBar","x-component-props":{},properties:{cancel:{type:"void",title:'{{ t("Cancel") }}',"x-component":"Action","x-component-props":{useAction:"{{ cm.useCancelAction }}"}},startImport:{type:"void",title:`{{ t("Start import", {ns: "${I}" }) }}`,"x-component":"Action","x-component-props":{type:"primary",htmlType:"submit",useAction:"{{ useImportStartAction }}"},"x-reactions":{dependencies:["upload"],fulfill:{run:"validateUpload($form, $self, $deps)"}}}}}}}}}}};return m.jsx(o.SchemaInitializerSwitch,H(B({},t),{checked:c,title:t.title,onClick:()=>{var h;if(c)return n();r["x-action-settings"].importSettings=Ie(i);const l=g.merge(r||{},t.schema||{});(h=t==null?void 0:t.schemaInitialize)==null||h.call(t,l),e(l)}}))},se=()=>{var l,h,s,p,f;const t=g.useField(),e=g.useFieldSchema(),{t:c}=C.useTranslation(),{dn:n}=o.useDesignable(),[u,i]=w.useState(),{importSettingsSchema:r}=z();return w.useEffect(()=>{i(r)},[t.address,(l=e==null?void 0:e["x-action-settings"])==null?void 0:l.importSettings]),m.jsxs(o.GeneralSchemaDesigner,{disableInitializer:!0,children:[m.jsx(o.SchemaSettingsModalItem,{title:c("Edit button"),schema:{type:"object",title:c("Edit button"),properties:{title:{"x-decorator":"FormItem","x-component":"Input",title:c("Button title"),default:e.title,"x-component-props":{}},icon:{"x-decorator":"FormItem","x-component":"IconPicker",title:c("Button icon"),default:(h=e==null?void 0:e["x-component-props"])==null?void 0:h.icon,"x-component-props":{}},type:{"x-decorator":"FormItem","x-component":"Radio.Group",title:c("Button background color"),default:(s=e==null?void 0:e["x-component-props"])!=null&&s.danger?"danger":((p=e==null?void 0:e["x-component-props"])==null?void 0:p.type)==="primary"?"primary":"default",enum:[{value:"default",label:'{{t("Default")}}'},{value:"primary",label:'{{t("Highlight")}}'},{value:"danger",label:'{{t("Danger red")}}'}]}}},onSubmit:({title:a,icon:x,type:v})=>{e.title=a,t.title=a,t.componentProps.icon=x,t.componentProps.danger=v==="danger",t.componentProps.type=v,e["x-component-props"]=e["x-component-props"]||{},e["x-component-props"].icon=x,e["x-component-props"].danger=v==="danger",e["x-component-props"].type=v,n.emit("patch",{schema:{"x-uid":e["x-uid"],title:a,"x-component-props":B({},e["x-component-props"])}}),n.refresh()}}),m.jsx(o.SchemaSettingsActionModalItem,{title:c("Importable fields"),schema:u,initialValues:B({},(f=e==null?void 0:e["x-action-settings"])==null?void 0:f.importSettings),components:{ArrayItems:X.ArrayItems},onSubmit:({importColumns:a,explain:x})=>{const v=a==null?void 0:a.filter(S=>{var b;return(b=S==null?void 0:S.dataIndex)==null?void 0:b.length}).map(S=>({dataIndex:S.dataIndex.map(b=>{var F;return(F=b.name)!=null?F:b}),title:S.title}));e["x-action-settings"].importSettings={importColumns:v,explain:x},n.emit("patch",{schema:{"x-uid":e["x-uid"],"x-action-settings":e["x-action-settings"]}}),n.refresh()}}),m.jsx(o.SchemaSettingsDivider,{}),m.jsx(o.SchemaSettingsRemove,{removeParentsIfNoChildren:!0,breakRemoveOn:a=>a["x-component"]==="Space"||a["x-component"].endsWith("ActionBar"),confirm:{title:c("Delete action")}})]})};class ie extends o.Plugin{load(){return R(this,null,function*(){this.app.use(te);const e={title:"{{t('Import')}}",Component:"ImportActionInitializer",schema:{"x-align":"right","x-decorator":"ACLActionProvider","x-acl-action":"importXlsx","x-acl-action-props":{skipScopeCheck:!0}},useVisible(){const n=o.useCollection_deprecated();return(n.template!=="view"||(n==null?void 0:n.writableView))&&n.template!=="file"&&n.template!=="sql"}},c=this.app.schemaInitializerManager.get("table:configureActions");c==null||c.add("enableActions.import",e),this.app.schemaInitializerManager.addItem("gantt:configureActions","enableActions.import",e),this.app.schemaSettingsManager.add(ye)})}}d.ImportActionInitializer=ae,d.ImportContextProvider=oe,d.ImportDesigner=se,d.ImportPlugin=ie,d.ImportPluginProvider=te,d.default=ie,d.useCurrentSchema=re,d.useDownloadXlsxTemplateAction=Q,d.useImportStartAction=Z,Object.defineProperties(d,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
