/* 故障报修
 * @Author: Li Hanlin
 * @Date: 2022-12-02 11:41:03
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-02-10 17:58:21
 */

import * as React from 'react';
import { useState, useMemo, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import Addform from '@/components/Addform';
import Detail from '@/components/RepaireDetail/Detail';
import dayjs from 'dayjs';
function Contract(props) {
  let actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
    open: false,
  }),
    [activeTabKey, setactiveTabKey] = useState('1'),
    [amount, camount] = useState(0);

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '编辑',
              val: 'edit',
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    if (row?.status == 1) {
      return (
        <PremButton
          pop={{
            title: '是否删除?',
            okText: '确认',
            cancelText: '取消',
            onConfirm: () => {
              run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
            },
          }}
          btn={{
            size: 'small',
            type: 'danger',
          }}
        >
          删除
        </PremButton>
      );
    } else {
      return <></>;
    }
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.columns;
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    if (activeTabKey == 1) {
      return defcolumn.concat({
        title: '操作',
        valueType: 'option',
        width: 150,
        render: (text, row, _, action) => [],
      });
    } else {
      return defcolumn;
    }
  }, [activeTabKey]);

  const pathconfig = useMemo(() => {
    let defpath = getcolumns(setdrawer).filter((it) => it.key == activeTabKey)[0]?.pathconfig ?? {};
    return defpath;
  }, [activeTabKey]);
  const calculateContractAmount = (list = [], month = 0) => {
    const sum = list?.reduce((prev, next) => {
      return (prev * 100 + next * 100) / 100;
    }, 0);
    camount(month == 0 || month ? (sum * 100) * month / 100 : 0);
  };
  const changeList = (list = []) => {
    list.forEach(it => {
      if (it.unitPrice && it.zxPrice) {
        it.rebatePrice = ((it.unitPrice ?? 0) * 100 - (it.zxPrice ?? 0) * 100) / 100;
      } else {
        it.rebatePrice = ''
      }
    });
    return list;
  };
  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">租赁合同</h3>}
        columns={columns}
        path={pathconfig?.list}
        actionRef={actionRef}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          name: '新增',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                open: true,
                item: {
                  registrationDate: dayjs().format('YYYY-MM-DD'),
                  contractEquipmentList: [
                    {
                      equipmentId: '',
                      unitPrice: '',
                      zxPrice: '',
                      rebatePrice: '',
                      deposit: '',
                      remark: ''
                    }
                  ]
                },
                title: '新增',
                val: 'add'
              }));
            },
          },
        }}
        tabList={getcolumns()}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          setactiveTabKey(key);
        }}
      />
      <DrawerPro
        fields={columns}
        detailpath={pathconfig?.detail || null}
        detailData={drawer?.item}
        defaultFormValue={drawer?.item}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...drawer}
        onFinish={(vals) => {
          console.log(vals);
          // if (drawer?.val == 'add') {
          //   run({ url: pathconfig?.add || '/add', params: { ...vals } });
          // } else if (drawer?.val == 'edit') {
          //   run({ url: pathconfig?.edit || '/edit', params: { ...vals, id: drawer?.item?.id } });
          // }
        }}
        onValuesChange={(changedValues, allValues) => {
          for (let i in changedValues) {
            if (i == 'contractEquipmentList' || i == 'tenancy') {
              calculateContractAmount(allValues['contractEquipmentList']?.map(it => it.unitPrice ?? 0), allValues['tenancy']);
            }
            if (i == 'contractEquipmentList') {
              let newList = changeList(allValues['contractEquipmentList']);
              formRef?.current?.setFieldsValue({ ['contractEquipmentList']: newList });
              setdrawer((s) => {
                return {
                  ...s,
                  item: { ...s.item, contractEquipmentList: newList }
                }
              })
            }
          }
        }}
        submitter={{
          render: (props, doms) => {
            return [
              <div key='render' className='spread' style={{ position: 'fixed', bottom: 12, width: 'calc(100% - 62px)' }}>
                <div key='amount' style={{ color: 'red', fontSize: 16, fontWeight: 500 }}>
                  <span>合同金额（单位：元）：</span>
                  <span>{amount}</span>
                </div>,
                <div>
                  <PremButton
                    key='rest'
                    btn={{
                      onClick: () => {
                        props.form?.resetFields()
                      },
                      style: { marginRight: 8 }
                    }}
                  >
                    重置
                  </PremButton>,
                  <PremButton
                    key='submit'
                    btn={{
                      type: "primary",
                      onClick: () => {
                        props.form?.submit?.()
                      },
                    }}
                  >
                    提交
                  </PremButton>,
                </div>
              </div>
            ];
          },

        }}
      >
        {/* {selectType(drawer?.val)} */}
      </DrawerPro>
    </div>
  );
}

export default Contract;
