/*
* 入驻店铺管理——入驻审核列表
* */
import { connect } from 'dva/index';
import React, { Component, Fragment } from 'react';
import { Form, Spin } from 'antd';
import {
  list_com_page_size_10,
  dragSldTableColumn,
  getTableNum,
  sldComLanguage,
  sldHandlePaginationData,
  sldtbaleOpeBtnText,
  list_com_page_more, sldIconBtn, failTip, sldPopConfirm, formItemLayoutModal, sucTip,
} from '@/utils/utils';
import global from '@/global.less';
import StandardTable from '@/components/StandardTable';
import Search from '@/components/Search/Search';
import router from 'umi/router';
import SldModal from '@/components/SldModal/SldModal';

let pageSize = list_com_page_size_10;
@connect(({ store, share }) => ({
  store, share,
}))
@Form.create()
export default class ApplyStoreList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      search_height: 0,
      initLoading: false,
      modalVisible:false,
      modalVisible_ok:false,
      scrollBarToTop: 0,//StandardTable滚动条是否返回顶部的标识，默认为0，不返回，逐渐加1
      data: {},//列表数据
      store_detail: {},
      selectedRows: [],
      selectedRowKeys: [],//selectedRows的key
      title: `${sldComLanguage('商品规格')}`,
      type: 'add',//'add'新增  'edit'编辑
      params: { pageSize: pageSize },//搜索条件
      submiting: false,
      modal_width: 500,
      operateData:[{
        type: 'select',
        label: `${sldComLanguage('拒绝理由')}`,//拒绝理由
        name: 'refuseReason',
        placeholder: `${sldComLanguage('拒绝理由')}`,//请选择拒绝理由
        sel_data: [],
        sele_key: 'reasonId',
        sele_name: 'content',
        diy: true,
        rules: [{
          required: true,
          message: `${sldComLanguage('拒绝理由')}`,//请选择拒绝理由
        }],
      },{
        type: 'textarea',
        label: `${sldComLanguage('备注')}`,//备注
        name: 'remark',
        placeholder: `${sldComLanguage('请输入审核拒绝理由，最多100字')}`,
        extra: `${sldComLanguage('最多输入100字')}`,
        maxLength: 100,
      }],
      store_business_info: [
        {
          type: 'select',
          label: `${sldComLanguage('开店时长')}`,
          name: 'openTime',
          placeholder: `${sldComLanguage('请选择开店时长')}`,
          sel_data: [],
          required: true,
          sele_key: 'value',
          sele_name: 'content',
          diy: true,
          rules: [{
            required: true,
            message: `${sldComLanguage('请选择开店时长')}`,
          }],
        }
      ],
      search_data: [
        {
        type: 'input',
        label: `${sldComLanguage('店铺名称')}`,
        name: 'storeName',
        placeholder: `${sldComLanguage('请输入店铺名称')}`,
      }, {
        type: 'input',
        label: `${sldComLanguage('店主账号')}`,
        name: 'vendorName',
        placeholder: `${sldComLanguage('请输入店主账号')}`,
      }, {
        type: 'select',
        label: `${sldComLanguage('店铺等级')}`,
        name: 'storeGradeId',
        placeholder: `${sldComLanguage('请选择店铺等级')}`,
        sel_data: [],
        diy: true,
        sele_key: 'gradeId',
        sele_name: 'gradeName',
      }, {
        type: 'select',
        label: `${sldComLanguage('审核状态')}`,
        name: 'state',
        placeholder: `${sldComLanguage('请选择审核状态')}`,
        sel_data: [
          { key: '', name: `${sldComLanguage('全部')}` },
          { key: '1', name: `${sldComLanguage('待审核')}` },
          // { key: '2', name: `${sldComLanguage('待付款')}` },
          { key: '3', name: `${sldComLanguage('已拒绝')}` },
        ],
      }],
      formValues: {},//搜索条件
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 50,
          render: (text, record, index) => getTableNum(this.state.params, pageSize, index),
        },
        {
          title: `${sldComLanguage('店铺名称')}`,
          dataIndex: 'storeName',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('店主账号')}`,
          dataIndex: 'vendorName',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('联系人')}`,
          dataIndex: 'contactName',
          align: 'center',
          width: 100,
        }, {
          title: `${sldComLanguage('联系电话')}`,
          dataIndex: 'contactPhone',
          align: 'center',
          width: 100,
        }, {
          title: `${sldComLanguage('店铺等级')}`,
          dataIndex: 'storeGradeName',
          align: 'center',
          width: 100,
        }, {
          title: `${sldComLanguage('入驻时间')}`,
          dataIndex: 'submitTime',
          align: 'center',
          width: 150,
        }, {
          title: `${sldComLanguage('审核时间')}`,
          dataIndex: 'applyTime',
          align: 'center',
          width: 150,
        }, {
          title: `${sldComLanguage('审核状态')}`,
          dataIndex: 'stateValue',
          align: 'center',
          width: 100,
        }, {
          title: `${sldComLanguage('拒绝理由')}`,
          dataIndex: 'refuseReason',
          align: 'center',
          width: 100,
          render: (text, record) => (text ? text : '--'),
        }, {
          title: `${sldComLanguage('备注')}`,
          dataIndex: 'auditInfo',
          align: 'center',
          width: 100,
          render: (text, record) => (text ? text : '--'),
        },
        {
          title: `${sldComLanguage('操作')}`,//操作
          align: 'center',
          width: 100,
          fixed:'right',
          render: (text, record) => (
            <Fragment>
              {record.state != 1
                ? sldtbaleOpeBtnText(`${sldComLanguage('查看')}`, () => this.goDetail(record))
                : sldtbaleOpeBtnText(`${sldComLanguage('审核')}`, () => this.goDetail(record))
              }
            </Fragment>
          ),
        },
      ],
    };
  }

  reason_list = [];

  componentDidMount() {
    this.get_list({ pageSize: pageSize });
    this.get_store_grade();
    this.get_reason_list();//获取审核拒绝的理由
    this.getStoreOpenTime();
    // this.get_detail_list();//获取各id对应的经营分类信息
    setTimeout(() => {
      this.resize();
    }, 500);
    window.addEventListener('resize', this.resize);
  }




  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.share.flag && nextProps.share.type == 'check_settle_store') {
      //审核导致的页面更新数据
      const { params, formValues } = this.state;
      this.get_list({ ...params, ...formValues });
      this.props.dispatch({
        type: 'share/updateDate',
        payload: { flag: true, type: 'edit_settle_store_info', sldGlobalShareData: {} },
      });
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
  }

  resize = () => {
    const { search_height } = this.state;
    if (this.refs.search_part != undefined) {
      if (this.refs.search_part.clientHeight != search_height) {
        this.setState({ search_height: this.refs.search_part.clientHeight });
      }
    }
  };

  goDetail = (val) => {
    router.push(`/manage_store/settle_store_list_apply_detail?id=${val.applyId}&state=${val.state}`);
  };

  //获取数据列表
  get_list = (params) => {
    this.setState({ initLoading: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'store/get_apply_store_list',
      payload: { ...params },
      callback: (res) => {
        this.setState({ initLoading: false });
        if (res.state == 200) {
          res.data.list.map(item=>{
            if(item.state != 1){
              item.disabled = true;
            }
          });

          if (res.data.length == 0 && this.state.params.current > 1) {
            params.current = params.current - 1;
            this.get_list(params);
          } else {
            this.setState({
              data: res.data,
            });
          }
        }
      },
    });
  };

  //获取开店时长列表
  getStoreOpenTime =  () => {
    let { store_business_info } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'store/get_store_open_time',
      callback: (res) => {
        if (res.state == 200) {
          let tmp_data = [];
          res.data.map(item => {
            tmp_data.push({ value: item, content: item + '年' });
          });
          for (let i in store_business_info) {
            if (store_business_info[i].name === 'openTime') {
              store_business_info[i].sel_data = tmp_data;
              break;
            }
          }
          this.setState({ store_business_info });
        }
      },
    });
  };

  //获取店铺列表
  get_store_grade = () => {
    let { search_data } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'store/get_grade_lists',
      payload: { pageSize: list_com_page_more },
      callback: (res) => {
        if (res.state == 200) {
          let tmp_data = search_data.filter(item => item.name == 'storeGradeId')[0];
          tmp_data.sel_data = res.data.list;
        }
        this.setState({ search_data });
      },
    });
  };


  handleSelectRows = (rows, rowkeys) => {
    this.setState({
      selectedRows: rows,
      selectedRowKeys: rowkeys,
    });
  };

  handleTablePagination = (pagination, filtersArg, sorter, type = 'main') => {
    let { formValues, scrollBarToTop } = this.state;
    if (type == 'main') {
      const params = sldHandlePaginationData(pagination, filtersArg, sorter, formValues);
      pageSize = params.pageSize;
      scrollBarToTop = scrollBarToTop + 1;
      this.setState({ params, scrollBarToTop });
      this.get_list(params);
    }
  };

  //表格拖动
  resizeTable = (index, size, type, data) => {
    let datas = dragSldTableColumn(index, size, data);
    this.setState({ [type]: datas });
  };

  //搜索事件
  search = (data) => {
    const values = { ...data };
    for (let i in values) {
      if (values[i] == '') {
        delete values[i];
      }
    }
    this.setState({
      formValues: values,
      params: { pageSize: pageSize },
    });
    this.get_list({ pageSize: pageSize, ...values });
  };
  //搜索重置事件
  seaReset = () => {
    //搜索条件置为空
    this.setState({
      formValues: {},
      params: { pageSize: pageSize },
    });
    this.get_list({ pageSize: pageSize });
  };


  //获取审核拒绝的理由
  get_reason_list = () => {
    const { dispatch } = this.props;
    let { operateData } = this.state;
    dispatch({
      type: 'common/get_reason_list',
      payload: { type: 103, isShow: 1 },
      callback: (res) => {
        if (res.state == 200) {
          for (let i in operateData) {
            if (operateData[i].name === 'refuseReason') {
              operateData[i].sel_data = res.data.list;
              break;
            }
          }
          this.reason_list = res.data.list;
          this.setState({ operateData });
        }
      },
    });
  };


  get_detail_list = (openTime) => {
    const { dispatch } = this.props;
    let { store_detail} = this.state;
    let parameter = {}
    parameter.applyIds = this.operate_ids
    this.setState({submiting:true})
    dispatch({
      type: 'store/get_apply_store_detail_list',
      payload: parameter,
      callback: res => {
        if (res.state == 200) {
          let scalingBindIdsArray = [];
          for (let i = 0; i < res.data.length; i++) {
            res.data[i].storeGoodsCateVOList.map(item => {
              scalingBindIdsArray.push(`${item.bindId}-${item.scaling}-${item.createVendorId}`);
            });
          }
          this.agree(openTime,scalingBindIdsArray);
        } else {
          failTip(res.msg);
        }
        this.setState({submiting:false})
      },
    });
  };

  //审核拒绝的method
  operate_ids = '';//当前操作的申请id串
  refuse = (ids) => {
    let { operateData } = this.state;
    operateData = JSON.parse(JSON.stringify(operateData));
    this.operate_ids = ids;
    this.setState({ modalVisible: true, operateData });
  }
//审核拒绝之后的弹框的取消method
  sldHandleCancle = () => {
    this.setState({ modalVisible: false ,modalVisible_ok: false});
  };
//审核拒绝之后的弹框的确定method
  sldHandleConfirm = (val) => {
    let selectd_reason = this.reason_list.filter(item => item.reasonId == val.refuseReason)[0];
    val.refuseReason = selectd_reason.content;
    val.isPass = false;
    val.applyIds = this.operate_ids;
    this.operate(val)
  };

//审核通过
  openAgreeModal = (ids) => {
    let { store_business_info } = this.state;
    store_business_info = JSON.parse(JSON.stringify(store_business_info));
    this.operate_ids = ids;
    this.setState({ modalVisible_ok: true, store_business_info });
  };

  agree = (openTime,scalingBindIdsArray)=>{
    let param = {};
    param.isPass = true;
    param.applyIds = this.operate_ids;
    param.openTime = openTime.openTime
    param.scalingBindIds = scalingBindIdsArray.join(',');
    this.operate(param);
  }

  operate = (id) => {
    const { params } = this.state;
    const { dispatch } = this.props;
    let param_data = {};
    let dis_type = 'store/check_applied';
    param_data = id;
    this.setState({submiting:true})
    dispatch({
      type: dis_type,
      payload: param_data,
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.get_list(params);
          this.setState({
            modalVisible:false,
            modalVisible_ok:false,
            selectedRows: [],
            selectedRowKeys: [],
          });
        } else {
          failTip(res.msg);
        }
        this.setState({submiting:false})
      },
    });
  };

  render() {
    const { selectedRows,selectedRowKeys, search_data, columns, initLoading, data, search_height, scrollBarToTop,modal_width,title,submiting,modalVisible,modalVisible_ok,operateData,store_business_info,show_foot } = this.state;
    return (
      <div className={global.common_page} style={{ flex: 1, paddingTop: 0 }}>
        <div className={global.tableListForm} ref={'search_part'}>
          <Search search_data={search_data}
                  seaSubmit={(data) => this.search(data)} seaReset={() => this.seaReset()}/>
        </div>
        {/*公共功能条-start*/}
        <div className={global.operate_bg}
             style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', flexDirection: 'row' }}>
            {selectedRowKeys.length == 0 ? sldIconBtn(() => {
              failTip(`${sldComLanguage('请先选中数据')}`);//请先选中数据
              //确认审核通过选中的商品吗？
            // }, `${sldComLanguage('审核通过')}`, 7, 0, 19, 19, 3, 'shenhetongguo', '#0fb39a') : sldPopConfirm('leftBottom', `${sldComLanguage('确认审核通过选中的商品吗？')}`, () => this.get_detail_list(selectedRowKeys.join(',')), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`, sldIconBtn(null, `${sldComLanguage('审核通过')}`, 7, 0, 19, 19, 3, 'shenhetongguo', '#0fb39a'), 0, 0, '#0fb39a')}
            }, `${sldComLanguage('审核通过')}`, 7, 0, 15, 15, 3, 'shenhetongguo', '#0fb39a') : sldIconBtn(() => this.openAgreeModal(selectedRowKeys.join(',')), `${sldComLanguage('审核通过')}`, 7, 0, 15, 15, 3, 'shenhetongguo', '#0fb39a')}

            {selectedRowKeys.length == 0 ? sldIconBtn(() => {
              failTip(`${sldComLanguage('请先选中数据')}`);//请先选中数据
              //确认审核拒绝选中的商品吗？
            }, `${sldComLanguage('审核拒绝')}`, 7, 0, 15, 15, 3, 'shenhejujue', '#fa0920') : sldIconBtn(() => this.refuse(selectedRowKeys.join(',')), `${sldComLanguage('审核拒绝')}`, 7, 0, 15, 15, 3, 'shenhejujue', '#fa0920')}
          </div>
        </div>
        {/*公共功能条-end*/}
        <Spin spinning={initLoading}>
          {/*标准表格-start*/}
          <StandardTable
            totalHeight={document.body.clientHeight - 130 - search_height - 20}
            bordered={false}
            scrollBarToTop={scrollBarToTop}
            selectedRows={selectedRows}
            data={data}
            rowKey={'applyId'}
            isCheck={true}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={(pagination, filtersArg, sorter) => this.handleTablePagination(pagination, filtersArg, sorter, 'main')}
            onSldHandleSeleRow={this.onSldHandleSeleRow}
            resizeTable={(index, size) => this.resizeTable(index, size, 'columns', columns)}
            isColumnResize={true}
          />
          {/*标准表格-end*/}
        </Spin>

        <SldModal
          title={`${sldComLanguage('审核拒绝理由')}`}
          width={modal_width}
          submiting={submiting}
          modalVisible={modalVisible}
          sldHandleConfirm={(val) => this.sldHandleConfirm(val)}
          sldHandleCancle={this.sldHandleCancle}
          formItemLayoutModal={formItemLayoutModal}
          content={operateData}
          show_foot={show_foot}
        />

        <SldModal
          title={`${sldComLanguage('审核批量通过')}`}
          width={modal_width}
          submiting={submiting}
          modalVisible={modalVisible_ok}
          sldHandleConfirm={(val) => this.get_detail_list(val)}
          sldHandleCancle={this.sldHandleCancle}
          formItemLayoutModal={formItemLayoutModal}
          content={store_business_info}
          show_foot={show_foot}
        />

      </div>
    );
  }
}
