/* 设备供应商
 * @Author: Li Hanlin
 * @Date: 2022-11-09 14:44:44
 * @Last Modified by: Li Hanlin
 * @Last Modified time: 2023-01-31 13:50:19
 */

import * as React from 'react';
import { useState, useMemo, useEffect, useRef } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import InitForm from '@/components/InitForm';
import ExtendField from '@/components/ExtendField';
import { doFetch } from '@/utils/doFetch';
import { Image, message, Divider } from 'antd';
import { ProDescriptions } from '@ant-design/pro-components';
const urlParams = {
  save: '/lease/umEquipmentSupplier/save',
  remove: '/lease/umEquipmentSupplier/deleteById',
  list: '/lease/umEquipmentSupplier/queryList',
  detail: '/lease/umEquipmentSupplier/queryById'
};
const detailcolumns = [
  {
    title: '供应商编号',
    dataIndex: 'supplierNo',
    key: 'supplierNo',
  },
  {
    title: '供应商名称',
    dataIndex: 'supplierName',
    key: 'supplierName',
  },
  {
    title: '纳税人识别号',
    dataIndex: 'taxpayerIdentificationNumber',
    key: 'taxpayerIdentificationNumber'
  },
  { title: '公司官网', dataIndex: 'companyWebsite', key: 'companyWebsite' },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '公司邮箱',
    dataIndex: 'companyEmail',
    key: 'companyEmail',
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
  },
  {
    title: '状态',
    dataIndex: 'statusName',
    key: 'status',
  },
  {
    title: '评分',
    dataIndex: 'score',
    key: 'score',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
];


const Details = ({ drawer }) => {
  const [newfieldscolumns, setnewfieldscolumns] = useState([]);
  const [request, setrequest] = useState();
  const selectValueType = (type, options) => {
    switch (type) {
      case 1:
        return {
          valueType: 'input',
        };
      case 2:
        return {
          valueType: 'select',
          options,
        };
      case 3:
        return {
          valueType: 'radio',
          options,
        };
      case 4:
        return {
          valueType: 'select',
          options,
        };
      default:
        break;
    }
  };

  useEffect(() => {
    fn();
    fn2();
  }, []);
  const fn = async () => {
    let res = await doFetch({
      url: '/base/paFormField/queryList',
      params: {
        formId: '3',
      },
    });
    if (res?.data?.dataList) {
      let column = [];
      res?.data?.dataList?.forEach?.((el) => {
        column.push({
          ...selectValueType(el.fieldChar, el.valueList),
          title: el.fieldName,
          dataIndex: el.id,
          key: el.id,
        });
      });
      setnewfieldscolumns(column);
    }
  },
    fn2 = async () => {
      const res = await doFetch({
        url: urlParams.detail,
        params: { id: drawer?.item?.id },
      });
      let obj = {};
      res?.data?.data['equipmentSupplierCharList']?.forEach?.((it) => {
        obj[it?.fieldId] = it?.fieldRealValue;
      });
      setrequest(
        {
          ...(res?.data?.data ?? {}),
          ...obj,
        } ?? {},
      );
    };
  return (
    <>
      <ProDescriptions dataSource={request} columns={detailcolumns} />
      <AutoTable
        pagetitle="联系信息"
        columns={[
          {
            title: '联系人',
            dataIndex: 'contactsName',
            key: 'contactsName',
            search: false,
            formItemProps: {
              rules: [
                {
                  required: true,
                  message: '此项为必填项',
                },
              ],
            },
          },
          {
            title: '手机号码',
            search: false,
            dataIndex: 'mobilePhone',
            key: 'mobilePhone',
          },
          {
            title: '邮箱',
            search: false,
            dataIndex: 'email',
            key: 'email',
          },
          {
            title: '职务',
            search: false,
            dataIndex: 'postName',
            key: 'postName',
            fieldProps: {
              placeholder: '请选择',
            },
            formItemProps: {
              rules: [
                {
                  required: false,
                  message: '此项为必填项',
                },
              ],
            },
          },
        ]}
        dataSource={request?.supplierContactsList}
        resizeable={false}
        pagination={false}
      />
      <Divider />
      <h3 className="page-title" style={{ marginBottom: 16 }}>
        扩展字段
      </h3>
      <ProDescriptions dataSource={request} columns={newfieldscolumns} />
    </>
  );
};
function Supplier(props) {
  let actionRef = useRef(),
    formRef = useRef();
  const [drawer, setDrawer] = useState({
    visible: false,
  });
  const edit = (text, row, _, action) => {
    return (
      <PremButton
        key='edit'
        btn={{
          size: 'small',
          onClick: () => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              // detailpath: urlParams.detail,
              // params: { id: row?.id },
              title: '编辑',
              val: 'only',
              type: 'edit',
              item: row
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        key='remove'
        pop={{
          title: '是否删除该供应商?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: async () => {
            let res = await doFetch({ url: urlParams.remove, params: { id: row.id } });
            if (res.code === '0000') {
              setDrawer((s) => ({
                ...s,
                visible: false,
              }));
              actionRef.current.reload();
            }
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };
  const columns = useMemo(() => {
    let defcolumn = getcolumns(false, actionRef);
    defcolumn[1].render = (text, row) => {
      return (
        <a
          onClick={() => {
            setDrawer((s) => ({
              ...s,
              visible: true,
              type: 'detail',
              item: row,
              val: 'only',
              title: row.supplierName + '的详细信息',
            }));
          }}
        >
          {row.supplierName}
        </a>
      );
    };
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [edit(text, row, _, action), remove(text, row, _, action)],
    });
  }, []);

  const selectMoreDrawerType = (type) => {
    switch (type) {
      case 'detail':
        return <Details drawer={drawer} />;
      case 'add':
        return (
          <ExtendField
            defaultFormValue={drawer?.item}
            setDrawer={setDrawer}
            drawer={drawer}
            actionRef={actionRef}
            columns={columns}
            formId={'3'}
            // urlParams={urlParams}
            onFinish={async (vals) => {
              let equipmentSupplierCharReqList = [];
              for (let i in vals) {
                if (!isNaN(Number(i))) {
                  equipmentSupplierCharReqList.push({
                    fieldId: i,
                    fieldRealValue: vals[i],
                  });
                  delete vals[i];
                }
              }
              let params = {
                ...vals,
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                equipmentSupplierCharReqList,
              };
              delete params.shopId;
              let res = await doFetch({
                url: urlParams.save,
                params,
              });
              if (res.code === '0000') {
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                }));
                actionRef.current.reload();
              }
            }}
          />
        );
      case 'edit':
        return (
          <ExtendField
            setDrawer={setDrawer}
            drawer={drawer}
            actionRef={actionRef}
            columns={drawer?.item?.statusChangeable == 1 ? getcolumns(false) : getcolumns(true)}
            formId={'3'}
            urlParams={urlParams}
            onFinish={async (vals) => {
              let equipmentSupplierCharReqList = [];
              for (let i in vals) {
                if (!isNaN(Number(i))) {
                  equipmentSupplierCharReqList.push({
                    fieldId: i,
                    fieldRealValue: vals[i],
                  });
                  delete vals[i];
                }
              }
              let params = {
                ...vals,
                id: drawer?.title == '编辑' ? drawer?.item?.id : '',
                equipmentSupplierCharReqList,
              };
              delete params.shopId;
              let res = await doFetch({
                url: urlParams.save,
                params,
              });
              if (res.code === '0000') {
                setDrawer((s) => ({
                  ...s,
                  visible: false,
                }));
                actionRef.current.reload();
              }
            }}
          />
        );
      default:
        return null;
    }
  };
  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">设备供应商</h3>}
        columns={columns}
        path={urlParams.list}
        actionRef={actionRef}
        pageextra={'add'}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setDrawer((s) => ({
                ...s,
                visible: true,
                item: {
                  status: 1,
                  score: 0,
                },
                title: '新增',
                detailpath: null,
                type: 'add',
                val: 'only',
              }));
            },
          },
        }}
      />

      <DrawerPro
        fields={columns}
        defaultFormValue={drawer?.item ?? {}}
        formRef={formRef}
        placement="right"
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            visible: false,
          }));
          actionRef.current.reload();
        }}
        {...drawer}
      >
        {selectMoreDrawerType(drawer?.type)}
      </DrawerPro>
    </div>
  );
}

export default Supplier;
