// Ñêðèïò èìïîðò èç Ôàðì-Ýêñïåðò (ÈíôîÀÑ)


const MaxDaysLimit = 14; // Ôèëüòð ñòàðûõ ôàéëîâ: áðàòü òîëüêî ôàéëû ñ äàòàìè íå ðàíåå MaxDaysLimit äíåé îò òåêóùåé

const UseBarcode = true; // îïðåäåëÿåò, áóäåò ëè èñïîëüçîâàòüñÿ øòðèõêîä, ïîñòàâëÿåìûé ïîñòàâùèêîì
      UseOutPrice = false;


      OUTPRICE_NAME = 'pdRetailCost';

var
    Dirname :string = 'c:\FarmX\docs\'; // êàòàëîã ïî÷òû. Åñëè íå óêàçàíî, òî ñêðèïò áóäåò çàïðàøèâàòü åãî ïðè êàæäîì îòêðûòèè.


var
    Header :TStringList; // ïðåäîïðåäåëåíà ïðèëîæåíèåì
    Data :TStringList; // ïðåäîïðåäåëåíà ïðèëîæåíèåì
    ExportAgent :string; // âñå îïðåäåëåíû ïðèëîæåíèåì
    Filename :string;

    ExportAgentName :string;
    ExportNakladNom :string;
    ExportNakladID_DOC :string;
    ExportNakladData :string;
    ExportNakladSklad :string;
    ExportSkladName :string;
    year,month,day :word;
    dt :tdatetime;

    Cena :currency;


const ListSeparator1 = ' îò ';
      ListSeparator2 = ' ïîñò.: ';
      ListSeparator3 = ' ñêë.: ';
      ListSeparator4 = ' ôàéë: ';



var Table :TClientDataset;
    num_doc :string;
    Item :variant;
    i :integer;
    OpenDialog :TOpenDialog;
    ThF_FIRSTPRICE,thf_SROK,thF_SrokSertif,ThF_NameSertif,thF_Amount,thF_NDS,
    thF_Name,thF_Seria,thF_Sertif,thF_NameProducer,thf_Tamog,
    thF_Country,thF_Regn,thF_Price,thF_BarCode,thF_DateSertif,thF_Em,thF_FirstProcent :TField;
    thF_Price_Reg :TField;
    thF_Price_RS :Tfield;
    thf_action_lab :tfield;
    str,str1 :string;
    Field :TField;

    InvoicesList :TStringList;

    List :TStringList;

    FileList :tstringlist;

    FibDB :TpFibDatabase = nil;

    function GetItemValue(Item :Variant; Name :String) :string;
    begin
       try
         result := vartostr(Item.attributes.getNamedItem(Name).value);
       except
         result := ''
       end;
    end;

    procedure AddStr(var Destination :string; const thField :tField; NULLVal :string = '');
    begin
      if (thField<>nil) and (thfield.asstring<>nullval)
      then Destination := Destination + thField.asstring;
      Destination := Destination + #9;
    end;

    procedure YYYYMMDDtoDT(var Destination :string; Field :tfield; Coalesce_Field :TField;  NULLVal :string = '');
    var strval :string;
    begin
      if (field<>nil) and (trim(field.asstring) = '')
      then Field := coalesce_field;

      if (field<>nil)
         and (field.asstring <> nullval)
         and (length(field.asstring)>=10)
      then begin
        strval := field.asstring;
        Destination := Destination + copy(strval,9,2)+'/'+copy(strval,6,2)+'/'+copy(strval,1,4);
      end;

      Destination := Destination + #9;
    end;


    function FindField(const Table :tDataset; const FieldNames :string; const FieldDescription :string) :TField;
    var List :TstringList;
        i :integer;
    begin
       result := nil;
       List := tstringlist.create;
       try
          stringtolist(FieldNames,List,';,');
          if list.count=0 then RaiseException('íå óêàçàíû èìåíà ïîëåé â ôóíêöèè FindField');

          for i := 0 to List.count-1 do
          begin
            Result := Table.findfield(List[i]);
            if result<>nil then break;
          end;
          if (Result=nil) and (FieldDescription>'') then RaiseException('íå íàéäåíî ïîëå "'+FieldDescription+'" ('+FieldNames+')');
       finally
          List.free;
       end;

    end;


    function IFSTR(BoolVal :boolean; const TrueVal :string; const FAlseVal :string = '') :string;
    begin
      if BoolVal then Result := TrueVal
      else Result := FalseVal;
    end;


    function GetValueFromListDialog(List :Tstrings) :string;
    var Form :TForm;
        ListBox :TListBox;
        Panel :TPanel;
        Btn :TButton;
    begin

      result := '';
      if List=nil then  exit;

      Form := TForm.create(nil);

      try
        ListBox := TListBox.create(Form);
        with Listbox do
        begin
          parent :=Form;
          Items.text := List.text;
          if List.count>0 then ItemIndex := 0;
          align :=alclient;
          Sorted := true;
        end;


        Form.caption := 'Âûáåðèòå íàêëàäíóþ:';
        form.position := poScreenCenter;
        form.borderstyle := bsDialog;
        form.width := 700;
        form.height := 400;
        Form.Font.Size := Form.Font.Size +2;

        Panel := tPanel.create(Form);
        with Panel do
        begin
          parent := Form;
          align := albottom;
          height := 35;
          BevelInner :=bvNone;
          BevelOuter := bvNone;

          (*
          with TBevel.create(Form) do
          begin
            Parent := panel;
            Align :=alTop;
            Shape := bsTopLine;
            Height := 4;
          end;
          *)

          Btn := TButton.create(Form);
          with Btn do
          begin
            Parent := Panel;
            Caption := 'Îòìåíà';
            ModalResult := mrCancel;
            Cancel := true;
            width := 70;
            Top := 6;
            Left := Form.ClientWidth - Width - 20;
          end;


          with TButton.create(Form) do
          begin
            Parent := Panel;
            Caption := 'Ok';
            ModalResult := mrOk;
            Default := true;
            Width := Btn.width;
            Top := Btn.Top;
            Left := Btn.left- Width -10;
          end;

        end;

        if form.showmodal = mrok then
        begin
          if ListBox.Itemindex <0
          then CreateHintW('Âû íå âûáðàëè íè îäíîé íàêëàäíîé')
          else Result := ListBox.Items[ListBox.Itemindex];
        end

      finally
        Form.free
      end;
    end;


 begin
     if filename = ''
     then begin
       if DirName = ''
       then begin
         DirName :=  AppIniFile.readstring('plugins_farmexpert','dirname','');
         //if not  SElectDirectory1(DirName,false,false,true) then exit;
         if not  SElectDirectory('Âûáåðèòå êàòàëîã ñ íàêëàäíûìè:','',DirName) then exit;
         DirName := Includetrailingpathdelimiter(DirName);
         AppIniFile.writestring('plugins_farmexpert','DirName',DirName);
       end
       else
         DirName := Includetrailingpathdelimiter(DirName);
     end
     else 
       DirName := extractfilepath(filename);

     InvoicesList:= Tstringlist.create;
     FileList := tstringlist.create;
     list := TStringList.create;
     Table := TClientDataset.Create(selfscript);


     with TMyWait.create('Èäåò èìïîðò íàêëàäíîé') do
     try

        if filename ='' then  GetFileList(DirName,FileList,'*.csv',false,true)
        else FileList.text := Filename;
        FileList.Sort;
        //filelist.savetofile('c:\temp\1.txt');

        for i := FileList.count-1 downto 0 do
        begin

          FileName := extractfilename(FileList[i]);
          dt := 0;
          if length(filename)<8 then continue;
          try
            year := strtointprotected(copy(filename,1,4));
            if (year>=1) and (year<=2100)
            then begin

              month := strtointprotected(copy(filename,5,2));
              if (month>=1) and (month<=12)
              then begin
                day := strtointprotected(copy(filename,7,2));
                if (day>=1) and (day<=31)
                then begin
                  dt := encodedate(year,month,day);
                  if dt< now - MaxDaysLimit then dt := 0;
                end;
              end
            end
          except
          end;

          if dt = 0
          then begin
            continue;
          end;


          //List.loadfromfile(DirName + FileList[i]);

          try
            ReadTXT(table,DirName + FileList[i]);

            if table.isempty
            then begin
              continue;
            end;

            Str := Table.fieldbyname('internalnumber').asstring + ListSeparator1
                   + Table.fieldbyname('internaldate').asstring + ListSeparator2
                   + Table.fieldbyname('provider').asstring + ListSeparator3
                   {+ Table.fieldbyname('client').asstring +'/'}+table.fieldbyname('address').asstring+ ListSeparator4
                   + filelist[i];

            InvoicesList.add(Str);


          except
            createhinte(exceptmessage,'Íå ìîãó ïðî÷èòàòü ôàéë '+FileList[i],20);
            continue;
          end;


        end;


        if InvoicesList.count=0
        then begin
            CreateHintW('Íàêëàäíûõ íå íàéäåíî');
            exit;
        end
        else begin
          if InvoicesList.count>1
          then begin
            Str := GetValueFromListDialog(InvoicesList);
            if str = '' then exit;
          end
          else Str := INvoicesList[0];
        end;


        Header.Values[ExportNakladNom] := copy(str,1,pos(listSeparator1,Str)-1);


        FileName := copy(str,pos(Listseparator4,Str)+length(ListSeparator4),length(Str));

        table.close;

        ReadTXT(table,DirName + FileName);

        //table.filter := '[DOCNUMBER]='+Quotedstr(Header.Values[ExportNakladNom]);  // åñëè â îäíîì ôàéëå îêàçàëîñü íåñêîëüêî íàêëàäíûõ, òî îòôèëüòðóåì ïî íîìåðó
        //Table.filtered := true;

        Header.Values[ExportNakladData] := copy(str,
                                                pos(listSeparator1,Str)+length(ListSeparator1),
                                                Pos(ListSeparator2,Str)-pos(listSeparator1,Str)-length(ListSeparator1));

        Header.Values[ExportAgentName] := copy(str,
                                                pos(listSeparator2,Str)+length(ListSeparator2),
                                                Pos(ListSeparator3,Str)-pos(listSeparator2,Str)-length(ListSeparator2));

        Header.Values[ExportSkladName] := copy(str,
                                                pos(listSeparator3,Str)+length(ListSeparator3),
                                                Pos(ListSeparator4,Str)-pos(listSeparator3,Str)-length(ListSeparator3));


        CreateHintI('Äàòà: ' + Header.Values[ExportNakladData]
                    +#13+' Íîìåð: '+ Header.Values[ExportNakladNom]
                    +#13+' Ïîñò.: '+ Header.Values[ExportAgentName]
                    );


        data.Clear;

        {
        list.Add('srok'#9'barcode'#9'sroksertif'#9'sertifname'#9+
          'upa'#9'nn'#9'article'#9'kart'#9'kol'#9'em'#9'rosn'#9'nds'#9'ed'#9+
          'name'#9'firstcena'#9'seria'#9'sertif'#9'analize'#9'producer'#9+
          'producername'#9'nalog5'#9'idanalize'#9'analizename'#9'datasertif'#9+
          'dateanalize'#9'reestrcena'#9'tamog'#9'producercountry'#9+
          'producercountryname'#9'maxprocent'#9'passport'#9'datepassport'#9+
          'sorti'#9'gost'#9'regn'#9'summa'#9'cena'#9'itogcena'#9'itogsumma');
        }


        thF_NAME := FindField(Table,'pdName','Íàèìåíîâàíèå òîâàðà');
        thF_NameProducer := FindField(Table,'pdProduction','Ïðîèçâîäèòåëü');
        thf_country := findfield(table,'pdCOUNTRY','Ñòðàíà');
        thF_AMOUNT := FindField(Table,'pdCount','Êîëè÷åñòâî åäèíèö');
        thF_Seria := FindField(Table,'pdSeries','Ñåðèÿ');
        thF_SROK :=  FindField(Table,'pdReleaseDate','Ñðîê ãîäíîñòè');
        thF_tamog := FindField(Table,'pdGTD','Íîìåð òàìîæåííîé äåêëàðàöèè');
        thF_Sertif := FindField(Table,'pdRegionCertificate' {'pdCetrtificate'},'Ñåðòèôèêàò');
        thF_DateSertif := findfield(table,'pdCERTIFICATEDATE','Äàòà âûäà÷è ñåðòèôèêàòà');
        thF_NAMESERTIF := FindField(Table,'pdCertificateCenter', 'Êåì âûäàí ñåðòèôèêàò');
        thF_RegN := nil; //FindField(Table,'pdRegionCertificate','Ðåãèñòðàöèîííûé íîìåð');
        thF_NDS := FindField(Table,'pdNDSPercent','Ñòàâêà ÍÄÑ');

        thF_FIRSTPRICE := FindField(Table, 'pdPlantCost','Öåíà çàâîäà');
        thF_FIRSTPROCENT := nil; //FindField(Table, 'PRC_NAC','% íàöåíêè');
        thF_SROKSERTIF := FindField(Table,'pdCertificateReleaseDate','Ñðîê äåéñòâèÿ ñåðòèôèêàòà');

        thF_Price := FindField(table,'pdSummaNDS','Ñóììà èòîãî');
        thf_action_lab := findfield(table,'adelta','');

        if UseBarcode
        then
          thF_Barcode := FindField(Table,'pdBarcode','Øòðèõêîä') // åñëè íåò, òî íå áóäåò îøèáêè
        else
          thf_Barcode := nil;

        thF_Em := nil; //findfield(table,'package','');
        thF_Price_reg := findfield(table,'pdRegisterCost','Öåíà ðååñòðà');


        if useoutprice
        then
          thF_Price_RS := FindField(table,OUtPrice_NAME,'')
        else
          thF_Price_RS := nil;

        data.Add('srok'#9'sroksertif'#9'sertifname'#9+
          'kol'#9'nds'#9+
          'name'#9+
          'firstcena'#9 +
          'seria'#9'sertif'#9+
          'producername'#9+
          'tamog'#9+
          'countryname'+#9+
          'regn'#9+
          'SUMMA'#9+ //ifstr(table.findfield('num_nak')<>nil,'cenanotnds','cena')+#9

          'barcode'+#9+
          'datesertif'+#9+
          'em'+#9+
          'price_reg'+#9+
          ifstr(useoutprice,'rs_cena'+#9,'')+
          //'action_lab'+#9+
          //'nn'+#9+
          //'producer'+#9
          );

        table.first;

        while not Table.eof do begin
          Str := '';

          yyyymmddtodt(str,thF_Srok,thF_SrokSertif);
          yyyymmddtodt(str,thF_SrokSertif,nil);
          Addstr(str,thF_NameSertif);
          Addstr(str,thF_Amount);
          Addstr(str,thF_NDS);
          Addstr(str,thF_Name);

          Addstr(str,thF_firstprice);


          Addstr(str,thF_Seria);
          Addstr(str,thF_Sertif);
          Addstr(str,thF_nameproducer);
          Addstr(str,thF_tamog);
          Addstr(str,thF_country);
          Addstr(str,thF_regn);
          Addstr(str,thF_price);
          Addstr(str,thF_barcode);
          yyyymmddtodt(str,thF_datesertif,nil);
          Addstr(str,thF_em);
          Addstr(str,thF_price_reg);
          if useoutprice then addstr(str,thf_price_rs);
          //Addstr(str,thF_action_lab,'0');

          //str :=  str +  GetCodeFromOSA(thf_name.asstring,false)  + #9;
          //str :=  str +  GetCodeFromOSA(thf_nameproducer.asstring,true)  + #9;

          data.Add(str);
          Table.Next;
        end;

     finally
       FileList.free;
       Invoiceslist.free;
       List.free;
       free
     end;

     createhint('Îïåðàöèÿ çàâåðøåíà');
 end.
