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