import { divider } from './config'
import { queryCustomerUrl, queryBranchUrl, queryProviderhUrl, consigneeUrl, queryCustomer_consignee_Url, queryProviderh_consignee_Url } from '../../api'
import { stationAttr } from '@/blocks/components/searchModalConfig'

function atuoRequired(self, baseName) {
  let form =self.form()
  if (baseName === 'consignee' && form) {
    let d_auto = form.getFieldValue(baseName + 'AutoDeliverySign')
    return !!d_auto
  } else if (baseName === 'shipper' && form) {
    let p_auto = form.getFieldValue(baseName + 'AutoPickUpSign')
    return !!p_auto
  }
}
export default class {
  constructor({ key, name, label }) {
    this.key = key
    this.name = name
    this.label = label
  }

  init(self) {
    console.log(self.$form)

    let pCascaderZone = require('@/blocks/components/cascaderZone').default
    let baseName = this.key
    let baseLabel = this.label
    let title = this.name
    let TYPE = this.key.toUpperCase() + '_TYPE'
    /**0=不显示,1=查看,2=新建,3=修改,4=复制 */
    // /**0=不显示, 1=新建，2=修改 ，3=查看 ，4=复制  */,
    let label = ['', '客户', '仓库', '供应商']
    const url = ['', queryCustomerUrl, queryBranchUrl, queryProviderhUrl]
    const url2 = ['', queryCustomer_consignee_Url, queryBranchUrl, queryProviderh_consignee_Url]
    let inputType = self.st == 1 ? 'txt' : 'input'
    let numberType = self.st == 1 ? true : false
    let searchModalType = self.st == 1 ? 'txt' : 'searchModal'
    let selectMode = self.st === 1 ? 'txt' : ''
    let checkList = ['ProvinceCity','PickUpSign', 'AutoPickUpSign', 'PickUpPicture', 'PickUpRail', 'DeliverySign', 'AutoDeliverySign', 'DeliveryPicture', 'DeliveryRail']

    let _field = [
      'SignTime',
      'SignTimeDura',
      'SignTimeUnit',
      'ProvinceCity',
      'Contact',
      'PhoneNumber',
      'LandlineNumber',
      'Email',
      'RelatedPhoneNumber',
      'Address',
      'Memo',
      'Latitude',
      'Longitude',
      'ProvinceName',
      'Province',
      'CityName',
      'City',
      'District',
      'DistrictName',
      'StationName','StationId','StationCode','DeliveryOrder','StationAreas'

    ]

    return [
      divider(self, title + '信息'),
      {
        name: baseName + 'Type',
        label: title + '类型',
        mode: self.st === 1 ? 'txt' : '',
        type: 'select',
        allowClear: false,
        required: self.st === 1 ? false : true,
        get value() {
          return self[baseName + 'Type']
        },
        get options() {
          //收货方类型 数据字典CONSIGNEE_TYPE:1客户 2仓库 3供应商
          return self.options[TYPE]
        },
        on: {
          change(value, label, options, form) {
            console.log(arguments);

            self[baseName + 'Type'] = value
            //1类型切换
            //主
            let filter = {
              [baseName + 'Name']: '',
              [baseName + 'Id']: '',
              [baseName + 'Code']: '',
            }
            if (baseName == 'consignee') {
              filter.returnOrderFlag = 0
              filter.consigneeReturnOrderPicture = 0
            }
            //子
            let consignee = [...checkList, ..._field].map((key) => {
              return baseName + key
            })

            let arr = { [baseName + 'UnitName']: '', [baseName + 'UnitId']: '', [baseName + 'UnitCode']: '' }

            if (value === 2) {
              //如果是仓库

              form.setFieldsValue(filter)
            } else {
              consignee = [...consignee, ...Object.keys(arr)]
            }
            consignee.forEach((key) => {
              filter[key] = ''
            })

            self.$nextTick(() => {
              form.setFieldsValue(filter)
            })
          },
        },
      },
      {
        name: baseName + 'UnitId',
        label: title + '单位ID',
        hidden: true,
      },
      {
        name: baseName + 'UnitCode',
        label: title + '单位code',
        hidden: true,
      },
      {
        get hidden() {
          return self[baseName + 'Type'] === 2
        },
        required: self.st === 1 ? false : true,
        targetClick: true,
        toolBar: {
          labelCol: { span: 8 },
          wrapperCol: { span: 16 },
          get items() {
            return [
              {
                type: 'input',
                name: 'customerCode',
                label: label[self[baseName + 'Type']] + '编码',
                value: '',
              },
              {
                type: 'input',
                name: 'customerName',
                label: label[self[baseName + 'Type']] + '名称',
                value: '',
              },
            ]
          },
        },
        get remoteUrl() {
          return {
            url: url[self[baseName + 'Type']],
            method: 'post',
          }
        },
        rowKey: 'id',
        targetValueKey: 'name',
        name: baseName + 'UnitName',
        value: '',
        label: title + '单位',
        get disabled() {
          return !self.cargoOwnerId ? true : false
        },
        remoteBefore: (node, res) => {
          res.data.cargoOwnerId = self.cargoOwnerId
        },
        type: searchModalType,
        on: {
          change(event, value, dataArr, form) {
            //2单位
            let obj = {
              [baseName + 'UnitId']: '',
              [baseName + 'UnitCode']: '',
            }
            let clearFieldValue = [..._field, ...['Id', 'Code', 'Name']]
            let data = dataArr[0]

            if (data && data.id) {
              // //客户或供应商
              data.deliveryRail = data.defaultDeliveryRail || 0
              data.pickUpRail = data.defaultPickUpRail || 0
              if (baseName !== 'consignee') {
                delete data.returnOrderDeadline
                delete obj.consigneeReturnOrderPicture
              } else {
                obj.returnOrderFlag = ~~data.returnOrderFlag
                obj.returnOrderDeadline = ~~data.returnOrderDeadline
                obj.consigneeReturnOrderPicture = ~~data.returnOrderPicture
              }
              obj[baseName + 'UnitCode'] = data.code
              obj[baseName + 'UnitId'] = data.id
              form.enableItem(baseName + 'Name')
              form.focusByName(baseName + 'Name')

              if (baseName == 'consignee') {
                const { deliverySignTimeUnit, deliverySignTimeDura, deliverySignTime } = data
                data.signTime = deliverySignTime;
                data.signTimeDura = deliverySignTimeDura;
                data.signTimeUnit = deliverySignTimeUnit;
              } else if (baseName === 'shipper') {
                const { pickUpSignTime, pickUpSignTimeDura, pickUpSignTimeUnit } = data
                  //发
                  data.signTime = pickUpSignTime;
                  data.signTimeDura = pickUpSignTimeDura;
                  data.signTimeUnit = pickUpSignTimeUnit;
              }
            } else {
              form.disableItem(baseName + 'Name')
              if (baseName == 'consignee') {
                obj.returnOrderFlag = 0
                obj.returnOrderDeadline = 0
                obj.consigneeReturnOrderPicture = 0
                obj.consigneeAutoDeliverySign = 0
                obj.consigneeDeliveryPicture = 0
                obj.consigneeDeliverySign = 0
              } else if (baseName == 'shipper') {
                obj.shipperPickUpSign=0
                obj.shipperAutoPickUpSign=0
                obj.shipperPickUpPicture=0
                obj.shipperPickUpRail= 0
              }
            }

            if (self[baseName + 'Type'] !== 2) {
              clearFieldValue.forEach((key) => {
                obj[baseName + key] = ''
              })
            }
            checkList.concat(['SignTime','SignTimeDura','SignTimeUnit']).forEach((key) => {
              let _key = key[0].toLowerCase() + key.slice(1)
              // obj[baseName + key] = ''
              if (data && data[_key] && data[_key] !== null) {
                obj[baseName + key] = data[_key]
              }
            })

            // 'SignTime','SignTimeDura','SignTimeUnit'

            form.setFieldsValue(obj)
            //请求

            let type = form.getFieldValue(baseName + 'Type')
            let str = ''
            if (type === 1) {
              str = 'customerId'
            } else if (type === 3) {
              str = 'providerId'
            } else {
              return
            }
            return self
              .axios({
                url: url2[self[baseName + 'Type']],
                method: 'post',
                data: {
                  [str]: obj[baseName + 'UnitId'],
                  pageNum: 1,
                  pageSize: 999,
                },
              })
              .then((response) => {
                if (response.success && response.data?.list?.length === 1) {
                  let data = response.data.list[0]
                  let clearFieldValue = [..._field]
                  let obj = {}

  //                  obj[baseName + 'DeliveryOrder'] = stationDeliveryOrder;

                  let { province, city, district,stationDeliveryOrder } = data
                  let arr = [province, city, district]
                  obj[baseName + 'Id'] = data.id
                  obj[baseName + 'Code'] = data.code
                  obj[baseName + 'Name'] = data.name

                  clearFieldValue.forEach((key) => {

                    let _key = key[0].toLowerCase() + key.slice(1)
                    //obj[baseName + key] = ''
                    if (data && data[_key] && data[_key] !== null) {
                      obj[baseName + key] = data[_key]
                    }
                  })
                  obj[baseName + 'DeliveryOrder'] = stationDeliveryOrder
                  obj[baseName + 'ProvinceCity'] = arr
                  delete obj[baseName + 'SignTime']
                  delete obj[baseName + 'SignTimeDura']
                  delete obj[baseName + 'SignTimeUnit']
                  form.setFieldsValue(obj)
                }
              })
          },
        },
        tableConfig: {
          get columns() {
            return [
              { dataIndex: 'id', title: 'ID', hidden: true },
              { dataIndex: 'name', title: label[self[baseName + 'Type']] + '名称' },
              { dataIndex: 'code', title: label[self[baseName + 'Type']] + '编码' },
            ]
          },
        },
      },

      {
        name: baseName + 'Id',
        label: title + 'ID',
        hidden: true,
      },
      {
        name: baseName + 'Code',
        label: title + 'code',
        hidden: true,
      },
      {
        targetClick: true,
        required: self.st === 1 ? false : true,
        toolBar: {
          labelCol: { span: 8 },
          wrapperCol: { span: 16 },
          get items() {
            return [
              {
                type: 'input',
                name: 'code',
                label: label[self[baseName + 'Type']] + '编码',
                value: '',
              },
              {
                type: 'input',
                name: 'name',
                label: label[self[baseName + 'Type']] + '名称',
                value: '',
              },
            ]
          },
        },
        get remoteUrl() {
          return {
            url: url2[self[baseName + 'Type']],
            //self[baseName + 'Type'] === 2 ? queryBranchUrl : consigneeUrl,
            method: 'post',
          }
        },
        rowKey: 'id',
        targetValueKey: 'name',
        remoteBefore: (vnode, remote, form) => {
          let id = form.getFieldValue(baseName + 'UnitId')
          let type = form.getFieldValue(baseName + 'Type')
          if (!id) {
            return false
          }
          if (type === 1) {
            remote.data.customerId = id
          } else if (type === 3) {
            remote.data.providerId = id
          }
        },
        name: baseName + 'Name',
        label: title,//收货方发货方
        get disabled() {
          return self[baseName + 'Type'] !== 2
        },
        type: searchModalType,
        on: {
          change(event, value, dataArr, form) {
            //3收货方改变时

            var data = dataArr[0]

            let clearFieldValue = [..._field]
            let obj = {}
            if (self[baseName + 'Type'] === 2) {
              clearFieldValue = clearFieldValue.concat(checkList)
            }
            if (data) {
              let { province, city, district ,stationDeliveryOrder} = data
              let arr = [province, city, district]
              obj[baseName + 'Id'] = data.id
              obj[baseName + 'Code'] = data.code

              if (self[baseName + 'Type'] === 2) {
                //仓库
                data.deliveryRail = data.defaultDeliveryRail || 0
                data.pickUpRail = data.defaultPickUpRail || 0
                obj[baseName + 'UnitId'] = data.id
                obj[baseName + 'UnitCode'] = data.code
                obj[baseName + 'UnitName'] = data.name


                // obj[baseName + 'StationAreas'] = stationAreas;
                // obj[baseName + 'StationCode'] = stationCode;
                // obj[baseName + 'StationId'] = stationId;
                // obj[baseName + 'StationName'] = stationName;



                if (baseName == 'consignee') {
                   //收
                  obj.consigneeReturnOrderPicture = ~~data.returnOrderPicture
                  obj.returnOrderFlag = 0
                  const { deliverySignTimeUnit, deliverySignTimeDura, deliverySignTime } = data
                  data.signTime = deliverySignTime;
                  data.signTimeDura = deliverySignTimeDura;
                  data.signTimeUnit = deliverySignTimeUnit;

                } else if (baseName === 'shipper') {
                  const { pickUpSignTime, pickUpSignTimeDura, pickUpSignTimeUnit } = data
                    //发
                    data.signTime = pickUpSignTime;
                    data.signTimeDura = pickUpSignTimeDura;
                    data.signTimeUnit = pickUpSignTimeUnit;
                }
              }
              clearFieldValue.forEach((key) => {
                let _key = key[0].toLowerCase() + key.slice(1)
                if (data){
                  obj[baseName + key] = data[_key]||''
                }
              })
              obj[baseName + 'DeliveryOrder'] = stationDeliveryOrder;
              obj[baseName + 'ProvinceCity'] = arr
            } else {
              clearFieldValue.forEach((key) => {
                if (!['SignTime', 'SignTimeDura', 'SignTimeUnit'].includes(key)) {
                  obj[baseName + key] = ''
                  }
              })

              if (self[baseName + 'Type'] === 2) {
                //仓库
                obj[baseName + 'UnitId'] = ''
                obj[baseName + 'UnitCode'] = ''
                obj[baseName + 'UnitName'] = ''
                obj[baseName + 'SignTime'] = ''
                obj[baseName + 'SignTimeDura'] = ''
                obj[baseName + 'SignTimeUnit'] = ''

                if (baseName == 'consignee') {
                  obj.consigneeReturnOrderPicture = 0
                  obj.returnOrderFlag = 0
                }
              }
            }

            form.setFieldsValue(obj)
          },
        },
        tableConfig: {
          get columns() {
            return [
              { dataIndex: 'id', title: 'ID', hidden: true },
              { dataIndex: 'name', title: label[self[baseName + 'Type']] + '名称' },
              { dataIndex: 'code', title: label[self[baseName + 'Type']] + '编码' },
            ]
          },
        },
      },

      self.st === 1
        ? {
          name: baseName + 'ProvinceCity',
          type: inputType,
          placeholder: '省/市/区',
          label: baseName == 'consignee' ? '目的地' : '始发地',
          readOnly: true,
          required: self.st === 1 ? false : true,
        }
        : {
          on: {
            change(value, arrValue, form) {
              if (arrValue && arrValue.length) {
                form.setFieldsValue({
                  [baseName + 'ProvinceName']: arrValue[0] ? arrValue[0].zname : '',
                  [baseName + 'Province']: arrValue[0] ? arrValue[0].zoneid : '',
                  [baseName + 'CityName']: arrValue[1] ? arrValue[1].zname : '',
                  [baseName + 'City']: arrValue[1] ? arrValue[1].zoneid : '',
                  [baseName + 'DistrictName']: arrValue[2] ? arrValue[2].zname : '',
                  [baseName + 'District']: arrValue[2] ? arrValue[2].zoneid : '',
                })
              }
            },
            popupVisibleChange(open, value) { },
          },
          level: 3,
          type: pCascaderZone,
          label: baseName == 'consignee' ? '目的地' : '始发地',
          name: baseName + 'ProvinceCity',
          required: self.st === 1 ? false : true,
        },

      { name: baseName + 'Contact', label: '联系人', type: inputType },
      {
        name: baseName + 'PhoneNumber',
        label: '手机号',
        type: inputType,
        rules: [
          {
            type: 'phone',
            //required: true
          },
        ],
      },
      {
        name: baseName + 'LandlineNumber',
        label: '座机号',
        type: inputType,
        rules: [
          {
            type: 'tel',
          },
        ],
      },
      {
        name: baseName + 'Email',
        label: '邮箱',
        type: inputType,
        rules: [
          {
            type: 'email',
            //required: true
          },
        ],
      },
      {
        name: baseName + 'RelatedPhoneNumber',
        label: '关联方手机号',
        get hidden() {
          return self[baseName + 'Type'] !== 1
        },
        type: inputType,
      },
      {
        name: baseName + 'Address', itemHeight: 'auto', label: '详细地址', wrapperCol: { span: 18 },
        required: self.st === 1 ? false : true, type: inputType
      },
      { name: baseName + 'Memo', label: '备注', type: inputType },
      { name: baseName + 'Latitude', label: '纬度', hidden: true },
      { name: baseName + 'Longitude', label: '经度', hidden: true },

      { name: baseName + 'ProvinceName', label: '省', hidden: true },
      { name: baseName + 'Province', label: '省id', hidden: true },
      { name: baseName + 'CityName', label: '市', hidden: true },
      { name: baseName + 'City', label: '市id', hidden: true },
      { name: baseName + 'DistrictName', label: '区', hidden: true },
      { name: baseName + 'District', label: '区id', hidden: true },
      {
        type: 'row',
        span: 24,
        itemHeight:'auto',
        labelCol: { span: 0 },
        wrapperCol: { span: 24 },
        list: [
          {
            ...stationAttr,
            name: baseName +'StationCode',
            label: '站点编码',
            span: 6,
            wrapperCol: { span: 16 },
            type:'searchModal',
            tableConfig: {
              ...stationAttr.tableConfig,
              remoteBefore: (vNode, reposts) => {
                if (self.record?.id) {
                //  reposts.data.excludeId =[self.record.id]
                }
              },
              getCheckboxProps: (record) => ({
                props: {
                 // disabled:self.record?.id==record.id ?? false
                },
              })
            },
            targetValueKey: 'code',
            on: {
              change(event, value, dataArr, form) {
                let data = dataArr[0];
                let f=['StationCode','StationName','StationId','DeliveryOrder','StationAreas']
                let obj = {  }
                if (!value) {
                  f.forEach(str => {
                    obj[baseName + str] = ''
                  });
                  return form.setFieldsValue(obj)
                } else {
                  let {  areas, name, code, id,deliveryOrder } = data
                  obj = {
                    [baseName + 'StationCode']: code,
                    [baseName + 'StationId']: id,
                    [baseName + 'StationName']: name,
                    [baseName + 'DeliveryOrder']: deliveryOrder,
                    [baseName + 'StationAreas']: areas,
                  }
                }
                form.setFieldsValue(obj)
              },

            }

          },
          {
            span:6,
            name: baseName +'StationName',
            label: '站点名称',
            placeholder: '请选择站点编码',
            wrapperCol: { span: 18 },
            type:'input'
          },
          {
            name:baseName+ 'StationId',
            label: '站点Id',
            hidden: true,
          },
          {
            span:6,
            wrapperCol: { span: 16 },
            name: baseName+'DeliveryOrder',
            label: '配送顺序',
            placeholder: '请输入整数和小数',
             min: -99999,
            type:'number'
          },
          {
            span:6,
            wrapperCol: { span: 16 },

            name: baseName+'StationAreas',
            label: '站点区域',
            type:'input'

          }
        ]
      },



      {
        type: 'row',
        span: 24,
        wrapperCol: { span: 24 },
        list: [
          {
            name: baseName === 'consignee' ? baseName + 'DeliverySign' : baseName + 'PickUpSign',
            readOnly: self.st == 1,
            offset: 1,
            type: 'check',
            span: 2,
            wrapperCol: { span: 24 },
            replaceFields: {
              true: 1,
              false: 0,
            },
            checkedText: baseLabel + '签到',
            value: 0,
          },
          {
            selfUpdate:false,
            name: baseName === 'consignee' ? baseName + 'AutoDeliverySign' : baseName + 'AutoPickUpSign',
            readOnly: self.st == 1,
            type: 'check',
            span: 2,
            checkedText: '自动签到',
            wrapperCol: { span: 24 },
            replaceFields: {
              true: 1,
              false: 0,
            },
            //options: [{ label: '自动签到', value: 1 }],
            value: 0,
            on: {
              change(value, form) {
                let f=[baseName + 'SignTime',baseName + 'SignTimeDura',baseName + 'SignTimeUnit']
                if (baseName === 'consignee') {
                 f.push('consigneeAutoDeliverySign',baseName + 'DeliveryRail')
                } else if (baseName === 'shipper') {
                  f.push('shipperAutoPickUpSign', baseName + 'PickUpRail')
                }

                f.forEach(name => {
                  form.setItemProps(name, {required:Boolean(value.target.checked) })

                })
              }
            }
          },
          {
            label: baseName === 'consignee' ? '送达签到时间点' : '提货签到时间点',
            type: 'row',
            span: 10,
            get required() {
              return atuoRequired(self, baseName)
             },
            labelCol: { span: 5 },
            wrapperCol: { span: 18 },
            list: [
              {
                get required() {
                  return atuoRequired(self, baseName)
                 },
                get disabled() {
                  return self.st === 1
                },
                name: baseName + 'SignTime',
                type: 'select',
                style: 'padding-right:6px',
                get options() {
                  let option = baseName === 'consignee' ? self.options.DELIVERY_SIGN_TIME : self.options.PICK_UP_SIGN_TIME
                  return self.options && option
                }
              },

              {
                get required() {
                  return atuoRequired(self, baseName)
                 },
                get disabled() {
                  return self.st === 1
                },
                type: 'number',
                name: baseName + 'SignTimeDura',
                style: 'padding-right:6px',

              },
              {
                get required() {
                  return atuoRequired(self, baseName)
                 },
                get disabled() {
                  return self.st === 1
                },
                name: baseName + 'SignTimeUnit',
                type: 'select',
                get options() {
                  return self.options && self.options.SIGN_TIME_UNIT
                },
                unit: '区间'
              }
            ]
          },


          {
            name: baseName === 'consignee' ? baseName + 'DeliveryPicture' : baseName + 'PickUpPicture',
            readOnly: self.st == 1,
            type: 'check',
            span: 2,
            checkedText: baseLabel + '图片',
            wrapperCol: { span: 24 },
            replaceFields: {
              true: 1,
              false: 0,
            },
            //options: [{ label: baseLabel + '图片', value: 1 }],
            value: 0,
          },

          {
            labelCol: { span: 8 },
            wrapperCol: { span: 10 },
            label: '默认' + baseLabel + '围栏',
            span: 6,
            unit: '千米',
            get required() {
              return atuoRequired(self, baseName)
             },
            // PickUpRail,DeliveryRail
            // defaultDeliveryRail        // consigneeDeliveryRail                 //shipperPickUpRail
            name: baseName === 'consignee' ? baseName + 'DeliveryRail' : baseName + 'PickUpRail',
            min: 0,
            tooltip: false,
            readOnly: numberType,
            type: self.st === 1 ? 'txt' : 'number',
            value: 0,
            /**0=不显示,1=查看,2=新建,3=修改,4=复制 */
            // /**0=不显示, 1=新建，2=修改 ，3=查看 ，4=复制  */,
          },
        ],
      },

    ]
  }

}
//['StationName','StationId','DeliveryOrder','StationAreas']
// @ApiModelProperty(value = "发货方站点ID")
// 	private Long shipperStationId;

// 	@ApiModelProperty(value = "发货方站点编号")
// 	private String shipperStationCode;

// 	@ApiModelProperty(value = "发货方站点名称")
// 	private String shipperStationName;

// 	@ApiModelProperty(value = "发货方站点区域")
// 	private String shipperStationAreas;

// 	@ApiModelProperty(value = "发货方配送顺序")
// 	private BigDecimal shipperDeliveryOrder;

// 	@ApiModelProperty(value = "收货方站点ID")
// 	private Long consigneeStationId;

// 	@ApiModelProperty(value = "收货方站点编号")
// 	private String consigneeStationCode;

// 	@ApiModelProperty(value = "收货方站点名称")
// 	private String consigneeStationName;

// 	@ApiModelProperty(value = "收货方站点区域")
// 	private String consigneeStationAreas;

// 	@ApiModelProperty(value = "收货方配送顺序")
// 	private BigDecimal consigneeDeliveryOrder;