import React, { useEffect, useState } from 'react';
import { connect, history } from 'umi';
import { Form, Card, Button, Collapse } from 'antd';
import { dispatchHandle } from '@/utils/publicHandle';
import { DescriptionForm } from '@/components/Customized/Description';
import classNames from 'classnames';
import utilsStyles from '@/utils/utils.less';
import AttributeMap from './Pane/AttributeMap';
import AttrPane from './Pane/AttrPane';
import { batchDicData } from '@/utils/utils';
import { BorderLeft } from '@/components/Customized/AutoTitle';
import ExpressionInfo from './ExpressionInfo';

const isBigScreenScale = window.innerWidth / 1600 > 1;
const { Panel } = Collapse;

const AttrEdit = (props) => {
  const {
    dispatch,
    match: { params },
    dict: { dicTotalsList },
    opsGather: { attrEnergyType, attrDataClass },
  } = props;
  const { meterId, id, type, meterName } = params;
  const name = decodeURIComponent(meterName);
  const isInfo = type === 'info';
  const [attrName, setAttrName] = useState();
  const [isEdit, setIsEdit] = useState(false);

  const [expression, setExpression] = useState([]);
  const [isCollect, setIsCollect] = useState(false);
  const [measureType, setMeasureType] = useState();

  /**
   * @表单提交
   */
  const [form] = Form.useForm();
  const handleSubmit = (e) => {
    e.preventDefault();
    form
      .validateFields()
      .then((values) => {
        const payload = { ...values, meterId, id };
        if (payload?.precision) payload.precision = Number(payload.precision);
        // values.bitValueIs = showBig
        dispatchHandle(dispatch, 'opsGather/device_service_meter_attr_patch', payload, () => {
          closeCurrentPage(`/ops/gather/instrument/config/${meterId}`);
        });
      })
      .catch(() => {});
  };
  /**
   * @页面方法
   */
  const goBack = () => {
    closeCurrentPage(`/ops/gather/instrument/config/${meterId}`);
  };
  /*
   * 页面数据
   */
  const JsonAttar = JSON.stringify(attrDataClass);
  const newAttar = JsonAttar.replace(/\bname\b/g, 'label').replace(/\bid\b/g, 'value');
  const aSelect = JSON.parse(newAttar);

  const { unit, energyUse, energyEfficiency, attrType } = batchDicData(
    ['unit', 'energyUse', 'energyEfficiency', 'attrType'],
    dicTotalsList,
  );
  const customChange = (checked) => {
    setIsCollect(checked);
    form.setFieldsValue({ energyTypeId: null });
  };
  const measureTypeChange = (val) => {
    setMeasureType(val);
  };

  const energyType =
    attrEnergyType?.length > 0 &&
    attrEnergyType.map((item) => ({
      label: item.name,
      value: item.id,
    }));
  const basicData = [
    {
      disabled: isInfo,
      label: '属性类型',
      name: 'attrGroupId',
      type: attrType.type,
      selectData: attrType.selectData,
    },
    { disabled: isInfo, label: '属性名称', name: 'name', type: 'input', onChange: setAttrName },
    {
      disabled: isInfo,
      label: '单位',
      name: 'unitId',
      type: unit.type,
      selectData: [{ label: '无', value: -1 }, ...unit.selectData],
    },
    {
      disabled: isInfo,
      label: '数据类型',
      name: 'dataTypeId',
      type: 'select',
      selectData: aSelect,
    },
    {
      disabled: isInfo,
      label: '精度',
      name: 'precision',
      type: 'select',
      selectData: [
        { label: '1', value: '0' },
        { label: '0.1', value: '1' },
        { label: '0.01', value: '2' },
        { label: '0.001', value: '3' },
        { label: '0.0001', value: '4' },
      ],
    },
    {
      disabled: isInfo,
      label: '是否是计量属性',
      name: 'measureIs',
      type: 'switch',
      onChange: customChange,
    },

    {
      show: isCollect,
      disabled: isInfo,
      required: true,
      label: '计量类型',
      name: 'measureType',
      type: 'select',
      selectData: [
        { label: '能耗', value: 1 },
        { label: '能效', value: 2 },
      ],
      onChange: measureTypeChange,
    },

    {
      show: measureType === 1,
      disabled: isInfo,
      label: '能源用途',
      name: 'energyUseId',
      type: energyUse.type,
      selectData: energyUse.selectData,
    },
    {
      show: measureType === 1,
      disabled: isInfo,
      label: '能耗类型',
      name: 'energyTypeId',
      type: 'select',
      selectData: energyType,
    },

    {
      show: measureType === 2,
      disabled: isInfo,
      label: '能效指标',
      name: 'energyEfficiencyId',
      type: energyEfficiency.type,
      selectData: energyEfficiency.selectData,
    },
  ];
  // if (isCollect) basicData.push({
  //   disabled: isInfo, label: '能耗类型', name: 'energyTypeId', type: 'select', selectData: energyType
  // })

  const getExpression = () => {
    dispatchHandle(dispatch, 'opsGather/device_service_meter_attr_id_get', { id }, (res) => {
      setAttrName(res.name);
      res.precision = String(res.precision);

      form.setFieldsValue(res);
      if (res?.expandObj?.attrExpression?.expressionItemList)
        setExpression(res.expandObj.attrExpression.expressionItemList);
      if (res?.measureType) setMeasureType(res.measureType);
    });
  };
  const onSaveExpress = (callback) => {
    const payload = {
      expandObj: {
        attrExpression: { expressionItemList: [] },
      },
    };
    payload['expandObj']['attrExpression']['expressionItemList'] = expression;
    dispatchHandle(
      dispatch,
      'opsGather/device_service_meter_attr_patch',
      { id, ...payload },
      () => {
        callback?.();
        getExpression();
      },
    );
  };
  const extraClick = (event) => {
    event.stopPropagation();
    if (!isEdit) setIsEdit(true);
    if (isEdit) onSaveExpress(setIsEdit(false));
  };
  const paneEditExtra = () => (
    <Button size="small" type="primary" onClick={extraClick}>
      {isEdit ? '保存' : '编辑'}
    </Button>
  );

  const getMeterAttarMap = () => {
    dispatchHandle(dispatch, 'opsGather/device_service_meter_attr_value_mapping_post', {
      meterAttrId: id,
    });
  };

  useEffect(() => {
    if (id) {
      getExpression();
      getMeterAttarMap();
      dispatchHandle(dispatch, 'opsGather/device_service_meter_attr_data_type_get');
      dispatchHandle(dispatch, 'opsGather/device_service_meter_post', { pageSize: 999 });
    }
    dispatchHandle(dispatch, 'opsGather/device_service_meter_model_attr_energy_type_get');
    dispatchHandle(dispatch, 'opsGather/device_service_meter_attr_data_class_get');
  }, []);

  return (
    <div className={classNames(utilsStyles.disFlexCol, utilsStyles.fullContainer)}>
      <Card size="small" style={{ flex: 1 }}>
        <Collapse defaultActiveKey={['1']}>
          <Panel showArrow={false} header="基础配置" key="1">
            <Form form={form} onFinish={handleSubmit}>
              <BorderLeft title="基础属性" style={{ marginBottom: 10 }} />
              <DescriptionForm columns={isBigScreenScale ? 4 : 3} data={basicData} />
              {!isInfo && (
                <div style={{ marginTop: 32, textAlign: 'right' }}>
                  <Button style={{ width: 100, height: 30, marginRight: 20 }} onClick={goBack}>
                    取消
                  </Button>
                  <Button style={{ width: 100, height: 30 }} type="primary" onClick={handleSubmit}>
                    保存
                  </Button>
                </div>
              )}
            </Form>
          </Panel>
          {id && (
            <Panel showArrow={false} header="属性配置" key="2" extra={!isInfo && paneEditExtra()}>
              {isEdit ? (
                <AttrPane
                  deviceInfo={{ id: parseInt(meterId, 10), name }}
                  attrId={id}
                  attrName={attrName}
                  expression={expression}
                  setExpression={setExpression}
                />
              ) : (
                <ExpressionInfo attrName={attrName} info={expression} />
              )}
            </Panel>
          )}
          {id && (
            <Panel showArrow={false} header="属性映射值" key="3">
              <AttributeMap isEdit={!isInfo} attrId={id} update={getMeterAttarMap} />
            </Panel>
          )}
        </Collapse>
        {isInfo && (
          <Button
            style={{ marginTop: 20 }}
            type="primary"
            onClick={() => history.push(`/ops/gather/instrument/config/${meterId}`)}
          >
            返回
          </Button>
        )}
      </Card>
    </div>
  );
};

export default connect(({ opsGather, dict, loading }) => ({
  opsGather,
  dict,
  loading: loading.models.opsGather,
}))(AttrEdit);