最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】全部剧本列表中添加剧本组和组成员列表

工作和技术 crifan 1129浏览 0评论
折腾:
【未解决】剧本编写系统中优化全部剧本列表页
期间,需要去
给页面中添加 剧本组和剧本成员列表
且支持从 全部剧本列表 页传入 group_id或 group_id,author_id
分别去匹配到对应的剧本组和 组成员
经过一番折腾,用代码:
现在已经可以支持显示剧本组和剧本成员列表了:
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Divider,
  Popconfirm,
  Tooltip,
  Select,
} from 'antd';
。。。
import { isString, isNumber } from '../../utils/utils';

const queryString = require('query-string');

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ script, topic, user, functionGroup, loading }) => ({
// @connect(({ script, topic, user, functionGroup }) => ({
    script,
  topic,
  currentUser: user.currentUser,
  // currentUserFunctionGroupList: user.currentUserFunctionGroupList,
  functionGroup,
  loading: loading.models.script,
}))
@Form.create()
export default class AllScriptList extends PureComponent {
  state = {
    formValues: {},
    currentPage: 1,
    pageSize: 20,
    first_level_topic: [],
    second_level_topic: [],
    groupList: [],
    groupMemberList: [],
  };


  componentWillMount() {
    console.log(`AllScriptList componentWillMount`)
    console.log(`this.props=`, this.props)
    const { currentUser} = this.props;
    console.log(`currentUser=`, currentUser)

    // const { functionGroup, members } = this.props;

    const { functionGroup: { functionGroup, functionGroups, members } } = this.props;
    console.log(`functionGroups=`, functionGroups)
    console.log(`functionGroup=`, functionGroup)
    console.log(`members=`, members)

  }

  componentDidMount() {
    console.log(`AllScriptList componentDidMount`)
    const { dispatch, currentUser} = this.props;
    console.log(`currentUser=`, currentUser)
    const { functionGroup: { functionGroups } } = this.props;
    console.log(`functionGroups=`, functionGroups)

    dispatch({
      type: 'user/fetchCurrent',
    }).then(() => {
    });

    // topic select 取所有的 topic
    const params = {
      page_size: 1000,
    };
    dispatch({
      type: 'topic/fetch',
      payload: params,
    });
    // }).then( () => {
    //   console.log("topic fetch callback: this=", this)
    //   this.fetchFunctionGroupCallback(this)
    // });


    const queryParamDict = this.generateQueryParamDict()
    this.updateScriptList(queryParamDict)
    // this.updateFunctionGroupsList(queryParamDict, this.fetchFunctionGroupCallback)
    this.updateFunctionGroupsList(this.fetchFunctionGroupCallback)
    // this.updateFunctionGroupsList(queryParamDict)
    // this.updateFunctionGroupsList()
  }


  onSecondLevelTopicChange(topicList, value) {
    const { form } = this.props;
    form.setFieldsValue({
      second_level_topic: value || '',
    });

    this.setState({
      second_level_topic: value || '',
    });
  }

  onFirstLevelTopicChange(topicList, value) {
    const { form } = this.props;
    form.setFieldsValue({
      topic: value,
      // second_level_topic: topicList[value][0] || '',
      second_level_topic:  '', // when first topic change, clear second topic
    });

    this.setState({
      first_level_topic: topicList[value],
      // second_level_topic: topicList[value][0] || '',
      second_level_topic: '', // when first topic change, clear second topic
    });
  }
。。。

  onGroupMemberListChange(groupMemberList, value) {
    console.log("onGroupMemberListChange: groupMemberList=", groupMemberList, ", value=", value)

    const { form } = this.props;
    form.setFieldsValue({
      author_id: value || '',
    });
  }

  onGroupListChange(groupList, value) {
    console.log("onGroupListChange: groupList=", groupList, ", value=", value)
    const { form } = this.props;
    form.setFieldsValue({
      group_id: value,
      author_id:  '', // when group change, clear author
    });

    const curGroupMemberList = this.getGroupMemberList(groupList, value)

    this.setState({
      groupMemberList: curGroupMemberList,
    });
  }

  updateScriptList(payload = {}){
    console.log("updateScriptList: payload=", payload)
    const { dispatch } = this.props

    dispatch({
      type: 'script/fetch',
      // payload: payload,
      payload,
    });
  }


  generateQueryParamDict(){
    const parsedQueryString = queryString.parse(this.props.location.search);
    console.log(`generateQueryParamDict: parsedQueryString=`, parsedQueryString)

    const queryParamDict = {}

    if (parsedQueryString) {
      const authorId = parsedQueryString.author_id;
      const groupId = parsedQueryString.group_id;
      console.log(`authorId=${authorId}, groupId=${groupId}`)

      if (authorId){
        queryParamDict.author_id = authorId
      }

      if (groupId){
        queryParamDict.group_id = groupId
      }
    }

    console.log(`queryParamDict=`, queryParamDict)
    return queryParamDict
  }

  // updateFunctionGroupsList(queryParamDict = {}, callback=undefined){
    updateFunctionGroupsList(callback=undefined){
    // console.log("updateFunctionGroupsList: queryParamDict=", queryParamDict, ", callback=", callback)
    console.log("updateFunctionGroupsList: callback=", callback)

    // Note: here only get SCRIPT function group, omit ADMIN function group
    const FUNCTION_GROUP_FUNCTION_SCRIPT = "1"
    // const curQueryParamDict = queryParamDict
    // curQueryParamDict.function = FUNCTION_GROUP_FUNCTION_SCRIPT
    const curQueryParamDict = {
      "function": FUNCTION_GROUP_FUNCTION_SCRIPT,
    }

    // // Note: when get group list, not consider group_id
    // if (curQueryParamDict.group_id) {
    //   delete curQueryParamDict.group_id
    // }
    console.log(`curQueryParamDict=`, curQueryParamDict)

    if(callback) {
      this.props.dispatch({
        type: 'functionGroup/fetch',
        payload: curQueryParamDict,
      }).then(callback(this));
    }else {
      this.props.dispatch({
        type: 'functionGroup/fetch',
        payload: curQueryParamDict,
      })
    }
  }

  /* eslint-disable class-methods-use-this */
  fetchFunctionGroupCallback(curThis){
    // console.log(`fetchFunctionGroupCallback: this=`, this)
    console.log(`fetchFunctionGroupCallback: curThis=`, curThis)
    const { functionGroup: { functionGroups } } = curThis.props;
    console.log(`fetchFunctionGroupCallback: functionGroups=`, functionGroups)
    if (functionGroups.results){
      const functionGroupList = functionGroups.results
      console.log("functionGroupList=", functionGroupList)

      curThis.updateGroupAndMember(functionGroupList)
    }
  }
  /* eslint-disable class-methods-use-this */

  getGroupMemberList(groupList, selectedGroupId) {
    console.log("getGroupMemberList: groupList=", groupList, ", selectedGroupId=", selectedGroupId)
    let selectedGroupIdInt = 0
    if (isString(selectedGroupId)) {
      selectedGroupIdInt = parseInt(selectedGroupId, 10)
    } else if (isNumber(selectedGroupId)) {
      selectedGroupIdInt = selectedGroupId
    }
    console.log("selectedGroupIdInt=", selectedGroupIdInt)

    let curGroupMemberList = []
    let curGroup
    for (const eachGroup of groupList){
      console.log("eachGroup=", eachGroup)
      if (eachGroup.id === selectedGroupIdInt){
        curGroup = eachGroup
        curGroupMemberList = eachGroup.members
        console.log("found curGroup=", curGroup, ", curGroupMemberList=", curGroupMemberList)
        break
      }
    }

    return curGroupMemberList
  }

  updateGroupAndMember(functionGroupList) {
    console.log("updateGroupAndMember: this", this)

    const queryParamDict = this.generateQueryParamDict()
    console.log(`before setFieldsValue queryParamDict=`, queryParamDict)
    const curGroupId = queryParamDict.group_id
    const curAuthorId = queryParamDict.author_id
    console.log(`curGroupId=${curGroupId}, curAuthorId=${curAuthorId}`)

    this.setState({
      groupList: functionGroupList || [],
    });

    this.props.form.setFieldsValue({
      group_id: curGroupId || "",
    });

    const { formValues } = this.state;
    console.log(`formValues=`, formValues)
    const newFormValues = {
      group_id: curGroupId || "",
      // author_id: curAuthorId || "",
      ...formValues,
    };
    console.log(`newFormValues=`, newFormValues)
    this.setState({
      formValues: newFormValues,
    });

    if (curGroupId) {
      // const curGroupIdInt = parseInt(curGroupId, 10)
      // console.log("curGroupIdInt=", curGroupIdInt)
      const curGroupMemberList = this.getGroupMemberList(functionGroupList, curGroupId)
      if (curGroupMemberList) {
        console.log("set curGroupMemberList=", curGroupMemberList)
        this.setState({
          groupMemberList: curGroupMemberList,
        });

        if (curAuthorId) {
          console.log("now to set curAuthorId=", curAuthorId)

          this.props.form.setFieldsValue({
            author_id: curAuthorId || "",
          });

          const { aboveFormValues } = this.state;
          console.log(`aboveFormValues=`, aboveFormValues)
          const newAboveFormValues = {
            author_id: curAuthorId || "",
            ...aboveFormValues,
          };
          console.log(`newAboveFormValues=`, newAboveFormValues)
          this.setState({
            formValues: newAboveFormValues,
          });
        }
      }
    }

  }


  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;

    const topicList = this.props.topic.topics;

    const firstLevelOptions = Object.keys(topicList).map(first => <Option key={first}>{first}</Option>);
    const secondLevelOptions = this.state.first_level_topic.map(second => <Option key={second}>{second}</Option>);

    console.log("renderSimpleForm")
    console.log("groupList=", this.state.groupList)
    console.log("groupMemberList=", this.state.groupMemberList)

    const groupOptions = this.state.groupList.map(eachGroup => <Option key={eachGroup.id}>{eachGroup.name}</Option>);
    const authorOptions = this.state.groupMemberList.map(eachAuthor => <Option key={eachAuthor.id}>{eachAuthor.username}</Option>);

    const selectFormItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 36 },
        sm: { span: 18 },
        md: { span: 16 },
      },
    };

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

          <Col md={8} sm={18}>
            <FormItem label="剧本组">
              {getFieldDecorator('group_id')(
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  onChange={this.onGroupListChange.bind(this, this.state.groupList)}
                  style={{ width: '100%' }}
                  placeholder="剧本组"
                >
                  {groupOptions}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={18}>
            <FormItem label="作者">
              {getFieldDecorator('author_id')(
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  onChange={this.onGroupMemberListChange.bind(this, this.state.groupMemberList)}
                  style={{ width: '100%' }}
                  placeholder="作者"
                >
                  {authorOptions}
                </Select>
              )}
            </FormItem>
          </Col>
。。。
        </Row>
      </Form>
    );
  }


  render() {
    const { script: { scripts }, loading } = this.props;
    const { currentPage, pageSize } = this.state;

    console.log("this.currentUser=", this.currentUser)

    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        rowKey: 'no',
        fixed: 'left',
        render(text, record, index) {
          const no = (currentPage - 1) * pageSize
          return no + index + 1;
        },
      },
      {
        title: '剧本组',
        dataIndex: 'joinedScriptGroup.groupName',
        rowKey: 'joinedScriptGroup.groupName',
      },
      {
        title: '作者',
        dataIndex: 'author',
        rowKey: 'author',
      },
      {
        title: 'Place',
        dataIndex: 'place',
        rowKey: 'place',
        width: 80,
      },。。。
      },
    ];

    return (
      <PageHeaderLayout title="组员剧本列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <SimpleTable
              loading={loading}
              data={scripts}
              columns={columns}
              scroll={{ x: 1800 }}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
其中:
获取所有的组,是调用后端Django接口:
127.0.0.1 – – [03/Aug/2018 09:06:24] “OPTIONS /api/v1/function_groups/?function=1 HTTP/1.1” 200 
得到的,所有组的列表的
是通过给FunctionGroupViewSet添加了list接口实现的:
class FunctionGroupViewSet(mixins.CreateModelMixin,
                           mixins.ListModelMixin,
                           mixins.RetrieveModelMixin,
                           PutOnlyUpdateModelMixin,
                           mixins.DestroyModelMixin,
                           viewsets.GenericViewSet):
    """
        功能组,有组长
    """
    queryset = FunctionGroup.objects.all()
    serializer_class = FunctionGroupSerializer
    permission_classes = (IsAuthenticated, IsUserFunctionAdmin)
    filter_backends = (OrderingFilter, SearchFilter)
    ordering_fields = ('created_at', )
    ordering = ('-created_at', )
    search_fields = ('name', 'description')

    def list(self, request, *args, **kwargs):
        """
            获取 function group 的列表
        """
        logger.info("FunctionGroupViewSet list: request=%s", request)

        function = request.query_params.get('function', '')
        group_id = request.query_params.get('group_id', '')
        logger.info("function=%s,group_id=%s", function, group_id)

        filter_condition = Q()
        if function:
            filter_condition = filter_condition & Q(function=function)

        if group_id:
            filter_condition = filter_condition & Q(id=group_id)

        logger.debug("filter_condition=%s", filter_condition)

        filteredFunctionGroup = FunctionGroup.objects.filter(filter_condition)
        logger.debug("filteredFunctionGroup=%s", filteredFunctionGroup)
        pagedFunctionGroup = self.paginate_queryset(filteredFunctionGroup)
        logger.info("pagedFunctionGroup=%s", pagedFunctionGroup)

        functionGroupSerializer = FunctionGroupSerializer(pagedFunctionGroup, many=True)
        logger.debug("functionGroupSerializer=%s", functionGroupSerializer)
        functionGroupSerializedData = functionGroupSerializer.data
        logger.debug("functionGroupSerializedData=%s", functionGroupSerializedData)

        respData = None
        if pagedFunctionGroup is not None:
            respData = self.get_paginated_response(functionGroupSerializedData)
        else:
            respData = Response(functionGroupSerializedData, status=status.HTTP_200_OK)
        logger.debug("respData=%s", respData)
        return respData
只传入group_id:

转载请注明:在路上 » 【已解决】全部剧本列表中添加剧本组和组成员列表

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
80 queries in 0.180 seconds, using 22.28MB memory