// Скрипт импорт из Фарм-Эксперт (ИнфоАС)


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.
