import { Card, Input, InputNumber, Table, Checkbox } from 'antd';
import { connect } from 'dva';
import React from 'react';
import { CascaderItem, ItemPicker, OrgPicker, Toolbar } from '@bizComponents';
import { FormEL, SuggestSelect, UdcSelect } from '@components';
import { ctrlUtils, formUtils } from '@utils';
// import { throttle, debounce } from 'lodash';

const { TextArea } = Input;
const { throttle } = ctrlUtils;

const cons = () => {
};

let _vdebug = cons;
const vdebug = throttle(800, false, () => _vdebug(), false); // debounce
// const vdebug = throttle(1000, false, () => _vdebug(), true)
const transCHToEN = (value, dispatch, targetKey, sourceKey) => {
  _vdebug = () => dispatch({ type: 'itemDetail/transCHToEn', payload: { value, targetKey, sourceKey } });
  vdebug();
};

const ItemDetail = ({ dispatch, itemDetail, loading, app }) => {
  const { mode, formData, otherProps, saveBtnHidden,controlDisable } = itemDetail;

  const domain = 'itemDetail';
  const domainCN = '历史';

  let readOnly = true,control=false;
  // const statusReadOnly = !(formData.itemStatus === undefined || formData.itemStatus === '0' || formData.itemStatus === '2');

  if (mode !== 'view') {
    readOnly = false;
  }
  // if (statusReadOnly) {
  //   readOnly = true;
  // }
  if (saveBtnHidden) {
    readOnly = true;
    // } else {
    //   readOnly = false
  }
  if(mode ==='update' && formData.itemStatus === '2' && controlDisable){
    control=true;
  }

  const handleUpdateProp = (value, index, key) => {
    // console.warn('pro', key, index, value)
    dispatch({
      type: 'itemDetail/updateOtherProps',
      payload: { value, index, key }
    });
  };

  const material = [{
    title: '物料编号',
    dataIndex: 'outerCode',
  }, {
    title: '物料名称',
    dataIndex: 'itemName',
    options: {
      rules: [{
        required: true,
        whitespace: true,
        message: '必填',
      }]
    },
    tag: <Input disabled={readOnly || control} maxLength={100} onChange={(e) => transCHToEN(e.target.value, dispatch, 'memCode', 'itemName')} />,
  }, {
    title: '半成品',
    dataIndex: 'semiProduct',
    tag: <Checkbox disabled={readOnly || control} checked={formData.semiProduct} />,
  }, {
    title: '物料类别',
    dataIndex: readOnly || control? 'cccCodeName' : 'cccCode',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: readOnly || control? undefined : <CascaderItem placeholder="请选择大类/中类/小类" />,
    // colProps: {
    //   xs: 16,
    //   sm: 16,
    //   md: 16,
    //   xl: 16,
    // },
    // formItemLayout: {
    //   labelCol: { span: 3, offset: 1 },
    //   wrapperCol: { span: 19 },
    // },
  }, {
    title: '临时编号',
    dataIndex: 'itemCode',
  }, {
    title: '品牌',
    dataIndex: 'brand',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        whitespace: true,
        message: '必填',
      }]
    },
    tag: <Input disabled={readOnly} maxLength={40} />,
    // tag: <UdcSelect domain="SRM" code="BRAND" disabled={readOnly} />,
    // tag: <SuggestSelect disabled={readOnly} apiName="brand" optionKey="code" />,
  }, {
    title: '盘点类型',
    dataIndex: 'itemStakeType',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <UdcSelect domain="SRM" code="ITEM_STAKE_TYPE" disabled={readOnly || control} />,
  }, {
    title: '物料缩写',
    dataIndex: 'memCode',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填',
      }]
    },
    tag: <Input disabled={readOnly || control} maxLength={40} />,
  }, {
    title: '对应标准原料',
    dataIndex: 'repItemName',
    options: {
      initialValue: '',
    },
    tag: <ItemPicker filter={{ statusList: [2], itemProp: 1 }} apiName="items" disabled={readOnly || control}/>,
  }, {
    title: '转换率',
    dataIndex: 'repItemRate',
    tag: <Input disabled={readOnly || !(formData.repItemName && formData.repItemName.id)} maxLength={18} />,
  }, {
    title: '仓库类型',
    dataIndex: 'whType',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填',
      }]
    },
    tag: <UdcSelect domain="SRM" code="WH_TYPE" disabled={readOnly || control} />,
  }, {
    title: '半成品库位',
    dataIndex: 'semiStore',
    tag: <UdcSelect domain="JDE" code="SEMI_STORE" disabled={readOnly || control} />,
  }, {
    title: '物料状态',
    dataIndex: 'itemStatusName',
  }, {
    title: '规格型号',
    dataIndex: 'spec',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        whitespace: true,
        message: '必填'
      }]
    },
    tag: <Input disabled={readOnly || control} maxLength={40} />,
  }, {
    title: '总账类',
    dataIndex: 'glpt',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <UdcSelect domain="JDE" code="GLPT" disabled={readOnly || control} />,
  }, {
    title: '产地',
    dataIndex: 'origin',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        whitespace: true,
        message: '必填'
      }]
    },
    tag: <Input disabled={readOnly} maxLength={40} />,
  }, {
    title: '含税单价',
    dataIndex: 'itemPrice',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag:
      <InputNumber
        disabled={readOnly || control}
        formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
        parser={value => value.replace(/\$\s?|(,*)/g, '')}
        style={{ width: '100%' }}
      />,
  }, {
    title: '主计量单位',
    dataIndex: 'uom',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        whitespace: true,
        message: '必填',
      }]
    },
    tag: <SuggestSelect apiName="udcItem" params={{ domainCode:"SRM",udcCode:"UOM"}} disabled={readOnly || control} />,
  }, {
    title: '消耗单位',
    dataIndex: 'uom10',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <SuggestSelect apiName="udcItem" params={{ domainCode:"SRM",udcCode:"UOM"}} disabled={readOnly || control} />,
  }, {
    title: '报货单位',
    dataIndex: 'uom9',
    tag: <SuggestSelect apiName="udcItem" params={{ domainCode:"SRM",udcCode:"UOM"}} disabled={readOnly || control} />,
  }, {
    title: '存储方式',
    dataIndex: 'storageMode',
    options: {
      rules: [{
        required: true,
        whitespace: true,
        message: '必填'
      }]
    },
    tag: <UdcSelect domain="ITEM" code="STOCK_CODE" disabled={readOnly || control} />,
  }, {
    title: '税种',
    dataIndex: 'taxCode',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        whitespace: true,
        message: '必填'
      }]
    },
    tag: <UdcSelect domain="SRM" code="TAX_CODE" disabled={readOnly || control} />,
  }, {
    title: '订货周期',
    dataIndex: 'orderPeriod',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        whitespace: true,
        message: '必填'
      }]
    },
    tag: <Input disabled={readOnly || control} maxLength={40} />,
  }, {
    title: '存储条件',
    dataIndex: 'storageCondition',
    options: {
      rules: [{
        required: true,
        whitespace: true,
        message: '必填'
      }]
    },
    tag: <Input disabled={readOnly} maxLength={40} />,
  }, {
    title: '税率(%)',
    dataIndex: 'taxRate',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <SuggestSelect disabled={readOnly || control} apiName="tax" />,
  }, {
    title: '采购应计税码',
    dataIndex: 'taxCodeInp',
    tag: <UdcSelect domain="JDE" code="TAX_FLAG" disabled={readOnly || control} />,
  }, {
    title: '销项税率(%)',
    dataIndex: 'taxRateOutp',
    tag: <SuggestSelect disabled={readOnly || control} apiName="tax" />,
  }, {
    title: '应纳销售税码',
    dataIndex: 'taxCodeOutp',
    tag: <UdcSelect domain="JDE" code="TAX_FLAG" disabled={readOnly || control} />,
  }, {
    title: '最小订货数量',
    dataIndex: 'moq',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag:
      <InputNumber
        disabled={readOnly || control}
        formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
        parser={value => value.replace(/\$\s?|(,*)/g, '')}
        style={{ width: '100%' }}
      />,
  }, {
    title: '保质期',
    dataIndex: 'storeValueDays',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <InputNumber
      disabled={readOnly || control}
      formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
      parser={value => value.replace(/\$\s?|(,*)/g, '')}
      maxLength={40}
      style={{ width: '100%' }}
    />,
  },
  // {
  //   title: '原料参数指标',
  //   dataIndex: 'itemParameter',
  //   options: {
  //     rules: [{
  //       required: true,
  //       whitespace: true,
  //       message: '必填'
  //     }]
  //   },
  //   tag: <Input disabled={readOnly} maxLength={40}/>,
  // },
  {
    title: '内部品牌',
    dataIndex: 'innerBrand',
    tag: <UdcSelect domain="ITEM" code="INNER_BRAND" disabled={readOnly} mode="multiple" />,
  }, {
    title: '要求部门',
    dataIndex: 'reqDept',
    // options: {
    //   rules: [{
    //     required: true,
    //     whitespace: true,
    //     message: '必填'
    //   }]
    // },
    tag: <OrgPicker disabled={readOnly || control}/>,
  }, {
    title: '物料创建原因',
    dataIndex: 'reqReason',
    options: {
      rules: [{
        required: true,
        message: '必填'
      }]
    },
    tag: <TextArea autosize={{ minRows: 2, maxRows: 6 }} />,
  }, {
    title: '用途',
    dataIndex: 'usage',
    options: {
      rules: [{
        required: true,
        message: '必填'
      }]
    },
    tag: <TextArea placeholder='用作哪些菜品' autosize={{ minRows: 2, maxRows: 6 }} />,
  }, {
    title: '采购员',
    dataIndex: 'poAgentCode',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <SuggestSelect disabled={readOnly || control} params={{ mode: mode }} apiName="purchases" optionKey='code' showCode={true} />,
  }, {
    title: '采购价格仓库',
    dataIndex: 'whProp',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <UdcSelect domain="SRM" code="WH_PROP" disabled={readOnly || control} />,
  }, {
    title: '配送类型',
    dataIndex: 'distProp',
    options: {
      rules: [{
        required: true && !formData.semiProduct,
        message: '必填'
      }]
    },
    tag: <UdcSelect domain="SRM" code="DIST_TYPE" disabled={readOnly || control} />,
  }, {
    title: '标准人工',
    dataIndex: 'stdLabCost',
    tag: <InputNumber disabled={readOnly || control}
      formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
      parser={value => value.replace(/\$\s?|(,*)/g, '')} style={{ width: '100%' }} />,
  }, {
    title: '标准制费',
    dataIndex: 'stdProdCost',
    tag: <InputNumber disabled={readOnly || control}
      formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
      parser={value => value.replace(/\$\s?|(,*)/g, '')} style={{ width: '100%' }} />,
  }, {
    title: '批处理类型',
    dataIndex: 'batType',
    tag: <UdcSelect domain="JDE" code="BAT_TYPE" disabled={readOnly || control} />,
  }];

  // 其他属性
  const columns1 = [{
    title: '行号',
    dataIndex: 'lineNo',
    width: '6%',
    key: 'lineNo',
  }, {
    title: '属性名称',
    dataIndex: 'otherProp',
    width: '31%',
    key: 'otherProp',
    render: (value, row, index) => {
      return (
        <Input
          size="small"
          value={value}
          disabled={readOnly || (formData.repItemName && formData.repItemName.id)}
          maxLength={40}
          onChange={(e) => {
            handleUpdateProp(e.target.value, index, 'otherProp');
          }}
        />
      );
    }
  }, {
    title: '属性值',
    dataIndex: 'otherPropValue',
    width: '31%',
    key: 'otherPropValue',
    render: (value, row, index) => {
      return (
        <Input
          size="small"
          value={value}
          disabled={readOnly}
          maxLength={40}
          onChange={(e) => {
            handleUpdateProp(e.target.value, index, 'otherPropValue');
          }}
        />
      );
    }
  }, {
    title: '标准物料属性值',
    dataIndex: 'standardPropValue',
    width: '31%',
    key: 'standardPropValue',
    render: (value, row, index) => {
      return (
        <Input
          size="small"
          value={value}
          disabled={readOnly || (formData.repItemName && formData.repItemName.id)}
          maxLength={40}
          onChange={(e) => {
            handleUpdateProp(e.target.value, index, 'standardPropValue');
          }}
        />
      );
    }
  }];

  const columns2 = [{
    title: '行号',
    dataIndex: 'lineNo',
    width: '6%',
    key: 'lineNo',
  }, {
    title: '属性名称',
    dataIndex: 'otherProp',
    width: '47%',
    key: 'otherProp',
    render: (value, row, index) => {
      return (
        <Input
          size="small"
          value={value}
          disabled={readOnly || (formData.repItemName && formData.repItemName.id)}
          maxLength={40}
          onChange={(e) => {
            handleUpdateProp(e.target.value, index, 'otherProp');
          }}
        />
      );
    }
  }, {
    title: '属性值',
    dataIndex: 'otherPropValue',
    width: '47%',
    key: 'otherPropValue',
    render: (value, row, index) => {
      return (
        <Input
          size="small"
          value={value}
          disabled={readOnly}
          maxLength={40}
          onChange={(e) => {
            handleUpdateProp(e.target.value, index, 'otherPropValue');
          }}
        />
      );
    }
  }];

  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];
    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: field[key],
      },
    });
  };

  const getDefaultValues = () => {
    const init = {};
    material.forEach((item) => {
      if (item.options && item.options.initialValue) {
        init[item.dataIndex] = item.options.initialValue;
      }
    });
    return init;
  };

  const handleSave = () => {
    formUtils.validateForm([...material], Object.assign(getDefaultValues(), formData), () => {
      dispatch({ type: `${domain}/save`, payload: getDefaultValues() });
    });
  };

  const handleCancel = () => {
    dispatch({ type: `${domain}/cancel` });
  };

  const buttons = [{
    id: 'save',
    text: '保存',
    onClick: handleSave,
    // hidden: saveBtn,
  }];

  return (
    <div>
      <Toolbar
        domain={domain}
        loading={loading}
        formData={formData}
        readOnly={readOnly}
        mode={mode}
        buttons={readOnly ? [] : buttons}
        handleCancel={handleCancel}
      />
      <Card title="物料信息" id="material">
        <FormEL items={material} record={formData} readOnly={readOnly} onFieldsChange={handleFormChange} />
      </Card>
      <Card
        id="otherProps"
        title="其他属性"
      >
        <Table
          size="small"
          columns={(formData.repItemName && formData.repItemName.id) ? columns1 : columns2}
          dataSource={otherProps}
          pagination={false}
        />
      </Card>
    </div>
  );
};

export default connect(({ itemDetail, loading, app }) => ({ itemDetail, loading, app }))(ItemDetail);
