import { Component, Input, OnInit, ViewChild, OnChanges, SimpleChanges } from '@angular/core';
import { SFComponent, SFSchema, SFUploadWidgetSchema } from '@delon/form';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer, of } from 'rxjs';
import { apiConf } from '@conf/api.conf';
import { SystemService } from '../../services/system.service';
const NOJSONTYPE = new Set([8, 12, 13]);

const IMAGECONFIG = {
  previewFile: (file: NzUploadFile) => of(file.url),
  action: apiConf.waterFileUpload,
  fileType: 'image/png,image/jpeg,image/jpg,image/gif',
  fileSize: 5120,
  limit: 1,
  limitFileCount: 1,
  resReName: 'data.fullFileWatermarkPath',
  urlReName: 'data.fullFileWatermarkPath',
  widget: 'upload',
  name: 'multipartFile',
  multiple: false,
  listType: 'picture-card'
} as SFUploadWidgetSchema;
@Component({
  selector: 'app-parterl-config',
  templateUrl: './config.component.html',
  styleUrls: ['./config.component.less']
})
export class PartnerSystemConfigComponent implements OnInit, OnChanges {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sf2', { static: false }) sf2!: SFComponent;

  @Input()
  configList: any[] = [];

  formDate: any = {
    isAudit: false,
    isEveryDay: false,
    isEveryWeek: false
  };
  labelWidth = 250;

  personServe!: number; // 个人提现手续费
  enterpriseServe!: number; // 企业提现手续费
  auditValue!: boolean; // 提现审核
  auditTime!: any; // 审核时间
  silenceClient!: number; // 沉默客户
  loseClient!: number; // 流失客户
  everyDay: any;
  auditTimeStatus: boolean = false;
  MonthDay: any;
  time: Date | null = null;
  defaultOpenValue = new Date(0, 0, 0, 0, 0, 0);
  tabs = [
    {
      name: '基础配置'
    },
    {
      name: '分享配置'
    }
  ];
  selectedTab = 0;
  TimeStatus: boolean = true;
  everyDayData: Array<any> = [];
  MonthDayData: any = [
    {
      month: [
        { label: '周一', value: '周一' },
        { label: '周二', value: '周二' },
        { label: '周三', value: '周三' },
        { label: '周四', value: '周四' },
        { label: '周五', value: '周五' },
        { label: '周六', value: '周六' },
        { label: '周日', value: '周日' }
      ],
      Times: [
        {
          startTime: [],
          endTime: []
        }
      ]
    }
  ];

  checkOptionsOne = [
    { label: '周一', value: '周一', checked: true },
    { label: '周二', value: '周二' },
    { label: '周三', value: '周三' },
    { label: '周四', value: '周四' },
    { label: '周五', value: '周五' },
    { label: '周六', value: '周六' },
    { label: '周日', value: '周日' }
  ];

  i: any;
  schema!: SFSchema;
  schema2!: SFSchema;

  // IMAGECONFIG = {
  //   widget: 'upload',
  //   action: `/scm/cms/cms/upload/multipartFile/fileModel`,
  //   limit: 1,
  //   limitFileCount: 1,
  //   resReName: 'url',
  //   urlReName: 'url',
  //   data: {
  //     appId: this.service.envSrv.getEnvironment().appId
  //   },
  //   multiple: false,
  //   listType: 'picture-card',
  //   showRequired: true
  // };

  constructor(private service: SystemService) {}
  ngOnChanges(changes: any): void {
    if (changes.configList) {
      console.log(changes.configList.currentValue[0]?.remark);
      this.personServe = changes.configList.currentValue[0]?.remark.personServe, // 个人提现手续费
      this.enterpriseServe= changes.configList.currentValue[0]?.remark.enterpriseServe, // 企业提现手续费
      this.auditValue=  changes.configList.currentValue[0]?.remark.auditValue, // 提现审核
      this.auditTime= changes.configList.currentValue[0]?.remark.auditTime, // 审核时间
      this.silenceClient= changes.configList.currentValue[0]?.remark.silenceClient, // 沉默客户
      this.loseClient= changes.configList.currentValue[0]?.remark.loseClient // 流失客户
      this.everyDayData= changes.configList.currentValue[0]?.remark.everyDayData // 流失客户
      this.MonthDayData= changes.configList.currentValue[0]?.remark.MonthDayData // 流失客户
      if (this.auditTime == '2') {
          // 每天
        this.auditTimeStatus = true;
          if(this.everyDayData){
            this.everyDayData = this.everyDayData
            this.everyDay = 1
          } else if(this.MonthDayData) {
          // 每周
          this.MonthDay = 2
          this.MonthDayData = this.MonthDayData
          this.TimeStatus =false
          }
      } else {
        this.auditTimeStatus = false;
      }
    }
  }

  ngOnInit() {
    this.initSF();
    this.everyDayData = [
      {
        startTime: '',
        endTime: ''
      }
    ];
  }
  addEvery() {
    this.everyDayData.push({
      startTime: [],
      endTime: []
    });
  }
  delEvery(index: number) {
    this.everyDayData.splice(index, 1);
  }
  addMonthEvery(value: any) {
    this.MonthDayData[value].Times.push({
      startTime: '',
      endTime: ''
    });
  }
  addMonth() {
    console.log(this.MonthDayData);
    if(this.MonthDayData) {
      this.MonthDayData.push({
        month: [
          { label: '周一', value: '周一' },
          { label: '周二', value: '周二' },
          { label: '周三', value: '周三' },
          { label: '周四', value: '周四' },
          { label: '周五', value: '周五' },
          { label: '周六', value: '周六' },
          { label: '周日', value: '周日' }
        ],
        Times: [
          {
            startTime: '',
            endTime: ''
          }
        ]
      });
    } else {
      this.MonthDayData = [
        {
          month: [
            { label: '周一', value: '周一' },
            { label: '周二', value: '周二' },
            { label: '周三', value: '周三' },
            { label: '周四', value: '周四' },
            { label: '周五', value: '周五' },
            { label: '周六', value: '周六' },
            { label: '周日', value: '周日' }
          ],
          Times: [
            {
              startTime: [],
              endTime: []
            }
          ]
        }
      ];
    }
    
  }
  delMonth(value: number, index: number) {
    this.MonthDayData[value].Times.splice(index, 1);
  }
  changeType(type: number): void {
    this.selectedTab = type;
  }
  changeMonth(type: any): void {
    console.log(type);
    console.log(this.MonthDayData);
  }
  everyDayChange(type: any): void {
    if (type) {
      this.MonthDay = false;
      this.TimeStatus = true;
    }
  }
  MonthDayChange(type: any): void {
    if (type) {
      this.everyDay = false;
      this.TimeStatus = false;
    }
  }

  initSF() {
    this.schema = {
      properties: {
        roadTransportPhoto: { title: '', type: 'string', ui: { hidden: true } },
        roadTransportPhotoWatermark: {
          type: 'string',
          title: '分享海报',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '支持JPG、PNG格式，文件小于2M（建议尺寸 750px*  1624 px）。',
            change: args => {
              if (args.type === 'success') {
                this.sf.setValue('/roadTransportPhoto', args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        share: { title: '', type: 'string', ui: { hidden: true } },
        shareWatermark: {
          type: 'string',
          title: '分享图',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '支持JPG、PNG格式，文件小于2M（ 建议尺寸 856px *  688px）。',
            change: args => {
              if (args.type === 'success') {
                this.sf.setValue('/share', args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        take: { title: '', type: 'string', ui: { hidden: true } },
        takeWatermark: {
          type: 'string',
          title: '受邀海报',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '支持JPG、PNG格式，文件小于2M（建议尺寸 750px*  1624 px）。',
            change: args => {
              if (args.type === 'success') {
                this.sf.setValue('/take', args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        complianceRemark: {
          title: '分享文案',
          type: 'string',
          maxLength: 50,
          ui: {
            placeholder: '请不要超过50个字',
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 6 }
          }
        }
      },
      required: ['roadTransportPhotoWatermark', 'shareWatermark', 'takeWatermark', 'complianceRemark']
    };
    this.schema2 = {
      properties: {
        roadTransportPhoto: { title: '', type: 'string', ui: { hidden: true } },
        roadTransportPhotoWatermark: {
          type: 'string',
          title: '分享海报',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '支持JPG、PNG格式，文件小于2M（建议尺寸750px*  1624 px）。',
            change: args => {
              if (args.type === 'success') {
                this.sf2.setValue('/roadTransportPhoto', args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        share: { title: '', type: 'string', ui: { hidden: true } },
        shareWatermark: {
          type: 'string',
          title: '分享图',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '支持JPG、PNG格式，文件小于2M（建议尺寸 856px *  688px）。',
            change: args => {
              if (args.type === 'success') {
                this.sf2.setValue('/share', args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        take: { title: '', type: 'string', ui: { hidden: true } },
        takeWatermark: {
          type: 'string',
          title: '受邀海报',
          ui: {
            ...IMAGECONFIG,
            descriptionI18n: '支持JPG、PNG格式，文件小于2M（建议尺寸750px*  1624 px）。',
            change: args => {
              if (args.type === 'success') {
                this.sf2.setValue('/take', args.fileList[0].response.data.fullFilePath);
              }
            }
          } as SFUploadWidgetSchema
        },
        complianceRemark: {
          title: '分享文案',
          type: 'string',
          maxLength: 50,
          ui: {
            placeholder: '请不要超过50个字',
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 6 }
          }
        }
      },
      required: ['roadTransportPhotoWatermark', 'shareWatermark', 'takeWatermark', 'complianceRemark']
    };
  }
  private uploadBefore = (file: any, fileList: any) => {
    return new Observable((observer: Observer<boolean>) => {
      const isLt1M = file.size / 1024 / 1024 < 2;
      const fileType = 'image/png,image/jpeg';
      if (fileType.indexOf(file.type) === -1) {
        this.service.msgSrv.warning('图片格式不正确！');
        observer.complete();
        return;
      }
      if (!isLt1M) {
        // this.service.msgSrv.warning('图片需小于1M');
        this.service.msgSrv.warning('图片大小超过2M!');
        observer.complete();
        return;
      }
      observer.next(isLt1M);
      observer.complete();
    });
  };
  changeAuto(value: any) {
    if (value == '2') {
      this.auditTimeStatus = true;
    } else {
      this.auditTimeStatus = false;
    }
  }
  save() {
    let params : any = {
      personServe: this.personServe, // 个人提现手续费
      enterpriseServe: this.enterpriseServe, // 企业提现手续费
      auditValue: this.auditValue, // 提现审核
      auditTime: this.auditTime, // 审核时间
      silenceClient: this.silenceClient, // 沉默客户
      loseClient: this.loseClient // 流失客户
    };
    if(this.auditTime == '2') {
      // 每天
      console.log(this.everyDay);
      console.log(this.MonthDay);
      
      if(this.everyDay){
        params.everyDayData = this.everyDayData
      } else if(this.MonthDay) {
      // 每周
      params.MonthDayData = this.MonthDayData
      }
    }
    const pra = Object.assign({}, ...this.configList)
    pra.remark =  JSON.stringify(params)
    this.service.request(this.service.$api_update_config_batch, [pra]).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改配置成功');
        setTimeout(() => {
          this.getConfigList(this.selectedTab);
        }, 100);
      }
    });
    
  }
  getConfigList(selectedTab: any) {
    this.selectedTab = selectedTab;
    this.service.request(this.service.$api_get_config_by_parent_id, { id: selectedTab?.id }).subscribe((res: Array<any>) => {
      if (res?.length > 0) {
        res = res.map(item => ({
          ...item,
          remark: item.remark ? JSON.parse(item.remark) : null,
          itemValue: item?.itemValue ? (NOJSONTYPE.has(item?.itemType) ? item?.itemValue : JSON.parse(item?.itemValue)) : item?.itemValue,
          itemData: item.itemData ? JSON.parse(item.itemData) : item.itemData
        }));
        const hiddenType = res.find(item => item.itemType === 7 || item.itemType === 999);
        this.labelWidth = hiddenType ? 0 : 250;
        this.configList = res;
      } else {
        this.configList = [];
      }
    });
  }
  private getImageModel(args: any, key: any) {
    return [
      {
        uid: key,
        name: 'LOGO',
        status: 'done',
        url: args.fileList[0].response.url,
        response: {
          url: args.fileList[0].response.url
        }
      }
    ];
  }
}
