<template>
  <div id="content-container" :class="{'expand-right': expandRight}">
    <page-loading :show="pageLoading"></page-loading>
    <!--Page Title-->
    <div id="page-title">
      <h1 class="page-header text-overflow">个人周报填报</h1>
    </div>

    <div class="page-content">
      <data-form
        element-loading-text="拼命加载中"
        :title="formTitle"
        :btnTitle="formBtnTitle"
        :schema="formSchema"
        :model="formModel"
        :showTitle="false"
        :btnData="formBtnData"
        ref="childrenForm"
        @radioValueChanged="radioValueChanged"
        @selectorValueChanged="selectorValueChanged"
        @addOption="setCascaderMultipleValue"
        @handleClose="handleClose"
      >
      </data-form>

    </div>
    <!--End Page content-->
  </div>
</template>

<script type="text/ecmascript-6">
import PageLoading from '../../../components/PageLoading.vue'
import DataForm from '../../../components/form/DataForm.vue'
import Api from '../../../server/index.js'
import {getItem} from '../../../config/mUtils.js'
import {baseUrl} from '../../../config/env.js'

export default {
  beforeRouteEnter (to, from, next) {
    next(function (vm) {
      global.getMenuIndex(vm)
    })
  },
  data () {
    return {
      expandRight: false,
      isSuperAdmin: false,
      draftDeptId: '',
      //form表单数据源
      loadingJudgeData: { //表单加载圈是否隐藏的判断数据源
        documentTypeDataDone: true,
        operationDone: true,
      },
      formTitle: '新增发文',
      formBtnTitle: '提交',
      formSchema: {},
      formModel: {},
      formProjectManagerData: [], // 项目负责人数据源
      formProjectAdmin: [],//项目管理员
      formBranchLeader: [],//分管领导
      formMainLeader: [],
      formPeopleData: [], //使用人的数据源
      formDocumentTypeData: [], //文种类型的数据源
      formFileData: [], //附件数据源
      formCustomizePeopleData: [],  //自定义人员选中数据
      draftManData: getItem('userName'), //拟稿人
      draftManId: getItem('userInfoId'), //拟稿人
      draftDeptNameData: eval(getItem('orgNameData')).join('>'),  //拟稿部门
      // nuclearManData: '',  //核稿人
      formMissionData: [],  //会签部门
      formMissionMemberData: [], //会签人员
      crossStatus: getItem('crossStatus'),
      //获取当前用户角色
      roles: JSON.parse(getItem('roles')),
      formPeopleWeightData: [],
    }
  },
  created () {
    this.judgeSuperAdmin()
    this.init()
    this.initFormData()
    this.getAllPeople()
    this.initFormSchema()
    // this.getPersonStatus();
    this.getDocumentType()
  },
  watch: {
    nuclearManData () {
      this.initFormData()
    },
//      formMissionMemberData() {
//        this.initFormSchema();
//      }
  },
  computed: {
    //判断加载圈是否能隐藏
    pageLoading: {
      get: function () {
        return !(this.loadingJudgeData.documentTypeDataDone && this.loadingJudgeData.operationDone)
      },
      set: function () {

      }
    }
  },
  methods: {
    // 判断form字段是否可以编辑
    judgeFormEditable (step) {
      return (this.canEdit && this.projectStep === step)
    },
    getAllPeople () {
      let params = {
        path: {
          id: 0
        }
      }
      Api.Administration.getPeers(params).then((result) => {
        this.loadingJudgeData.peopleDataDone = true
        this.loadingJudgeData.formProjectAdmin = true
        if (result.status === 0) {
          this.formProjectManagerData = this.assembleOrgData(result.data)
          this.formProjectAdmin = this.assembleOrgData(result.data)
          this.formBranchLeader = this.assembleOrgData(result.data)
          this.formMainLeader = this.assembleOrgData(result.data)
          this.formPeopleData = this.assembleOrgData(result.data)
        } else {
          this.$message.error(result.msg)
        }
      })
    },
    init () {
      let orgIdArray = JSON.parse(getItem('orgIdData'))
      let userInfoId = getItem('userInfoId')
      let orgId = orgIdArray[orgIdArray.length - 1]
      this.draftDeptId = orgId
      Api.PersonnelManagement.personLeaderMember(orgId).then((result) => {
        if (result.status === 0) {
          let memberList = []
          for (let member of result.data) {
            memberList.push(member.personName)
            this.formPeopleData.push(member.personName)
          }
          this.formModel.nuclearMan = memberList.join('，')
          if (!this.formModel.isSigned) {
            this.formModel.signedPerson = memberList.join(',')
          }
        }
      })
      let orgList = []
      Api.Common.getOrganization().then((result) => {
        if (result.status === 0) {
          orgList = result.data[0].childList
          for (let org of orgList) {
            this.formMissionData.push({
              label: org.name,
              model: org.id
            })
          }
          if (!this.formModel.isSigned) {
            this.formModel.signedDepts.push(orgId)
            this.formModel.executeDepts.push(orgId)
            this.getSignedMember()
          }
        }
      })
      let params = {
        path: {
          id: 0
        }
      }
      Api.Administration.getPeers(params).then((result) => {
        if (result.status === 0) {
          this.formPermissionsData = this.assembleOrgData(result.data)
        } else {
          this.$message.error(result.msg)
        }
      })
    },
    //判断是否是超级管理员
    judgeSuperAdmin () {
      this.isSuperAdmin = (getItem('userId') == 0)
    },
    /*
     * form相关
     */
    //获取表单数据源
    initFormData () {
      this.formModel = {
        step: 0,
        draftMan: this.draftManData,
        draftManId: this.draftManId,
        draftDeptId: this.draftDeptId,
        draftDeptName: this.draftDeptNameData,
        projectName: '',
        copying: '',
        cC: '',
        difficultyFactor: 1,
        isSigned: false,
        signedDepts: [],
        executeDepts: [],
        signedPerson: '',
        openRange: '',

        permissionsPeople: [],
        projectAdmin:[],
        branchLeader:[],
        MainLeader:[],
        // permissions: 0,
        // nuclearMan: '',
        // contentTitle: '',
        // contentClass: '',
        // CategoryID: '',
        receiveNum: '',
        gross: '',
        budget: '',
        // budgetRate: '',
        // contRate: '',
        scheme: '',
        goal: '',
        // content: '',
        membersList: [],
        // imprintNum: '',
        endDate: '',
        fileData: [],
        imprintDate: '',
        documentType: 2,
        year: moment().format('YYYY'),
      }
      this.formBtnData = [
        {
          title: this.formBtnTitle,
          type: 'primary',
          callback: () => {
            if (this.formValidate()) {
              this.formSubmit()
            }
          }
        },
        {
          title: '取消',
          type: 'default',
          callback: () => {
            this.$router.go(-1)
          }
        },
      ]
    },
    validateMultipleOfHalf(rule, value, callback) {
      if (value === undefined || value === null || value === '') {
        return callback(new Error('请输入一个值'));
      }

      const num = parseFloat(value);

      if (isNaN(num)) {
        return callback(new Error('工作量必须为数字值'));
      }

      if ((num * 2) % 1 !== 0) {
        return callback(new Error('工作量必须是 0.5 的倍数'));
      }

      callback(); // 通过验证
    },
    validateMultipleOfHalf1(rule, value, callback) {
      if (value === undefined || value === null || value === '') {
        return callback(new Error('请输入一个值'));
      }

      const num = parseFloat(value);

      if (isNaN(num)) {
        return callback(new Error('周数必须为数字值'));
      }

      if (num <= 0 || num % 1 !== 0) {
        return callback(new Error('周数必须是正整数'));
      }

      callback(); // 通过验证
    },
    initFormSchema () {
      this.formSchema = [
        {
          type: 'custom-input',
          title: '姓名',
          model: 'draftMan',
          externalValue: {
            disabled: true
          }
        },
        {
          type: 'custom-input',
          title: '部门',
          model: 'draftDeptName',
          externalValue: {
            disabled: true
          }
        },
        {
          type: 'custom-dynamic',
          title: '新增个人周报',
          model: 'membersList',
          externalValue: {
            btnData: {
              title: '新增',
              callback: () => {
                this.formPeopleWeightData.push(
                  {
                    span: 24,
                    model: {
                      projectName: '',
                      workload: '',
                      week: '',
                      thisWeek: '',
                      nextWeek: '',
                    },
                    schema: [
                      {
                        type: 'custom-input',
                        title: '项目名称',
                        model: 'projectName',
                        span: 7,
                        rules: [
                          {required: true, message: '项目名称不能为空'}
                        ],
                        externalValue: {}
                      },
                      {
                        type: 'custom-input',
                        title: '工作量',
                        model: 'workload',
                        span: 5,
                        rules: [
                          { required: true, message: '工作量不能为空' },
                          { type: 'number',
                            validator: this.validateMultipleOfHalf,
                            trigger: 'blur'}
                        ],
                        externalValue: {}
                      },
                      {
                        type: 'custom-input',
                        title: '周数',
                        model: 'week',
                        span: 5,
                        rules: [
                          {required: true, message: '周数不能为空'},
                          { type: 'number',
                            validator: this.validateMultipleOfHalf1,
                            trigger: 'blur'}
                        ],
                        externalValue: {}
                      },
                      {
                        type: 'custom-textarea',
                        title: '本周进展',
                        model: 'thisWeek',
                        span: 24,
                        rules: [
                          {required: true, message: '本周进展不能为空'}
                        ],
                        externalValue: {}
                      },
                      {
                        type: 'custom-textarea',
                        title: '下周计划',
                        model: 'nextWeek',
                        span: 24,
                        rules: [
                          {required: true, message: '下周计划不能为空'}
                        ],
                        externalValue: {}
                      },
                      {
                        type: 'delete',
                        callback: (index) => {
                          this.formPeopleWeightData.splice(index, 1)
                          this.formModel.membersList = this.formPeopleWeightData
                          this.initFormSchema()
                        }
                      },
                    ],
                  },
                )
                this.formModel.membersList = this.formPeopleWeightData
                this.initFormSchema()
              }
            },
            dynamicData: this.formPeopleWeightData
          }
        },
        {
          type: 'submit'
        }
      ]
    },
    getPersonStatus () {
      /*根据账号ID,查询人员信息*/
      let id = this.formModel.draftManId
      // alert(id);
      Api.PersonnelManagement.personDocumentNew(id).then((result) => {
        if (result.status === 0) {
          let personBaseFormModel = result.data.ext
          this.crossStatus = personBaseFormModel.crossStatus
        } else {
          this.$message.info(result.msg)
        }
      })
    },

    //获取文种
    getDocumentType () {
      let param = {
        query: {},
        data: {
          category: 'publicationCategory',
        }
      }
      //判断只有协会的人员可以选择所有的发文,技交所人员不能选择鄂技协和鄂技协纪要
      Api.SystemSetting.getBaseData(param).then((result) => {
        this.loadingJudgeData.documentTypeDataDone = true
        if (result.status === 0) {
          var role = this.roles
          console.log(this.roles)
          /*if(this.crossStatus == 2 || this.crossStatus == 1){
            for (let i = 0; i < result.data.length; i++) {
              let purchaseItem = result.data[i];
              this.formDocumentTypeData.push({
                model: purchaseItem.id,
                label: purchaseItem.termName
              });
            }
          }else{
            for (let i = 0; i < result.data.length; i++) {
              let purchaseItem = result.data[i];
              if(purchaseItem.termNo != 12 && purchaseItem.termNo != 13){
                this.formDocumentTypeData.push({
                  model: purchaseItem.id,
                  label: purchaseItem.termName
                });
              }

            }
          }*/
          for (let i = 0; i < result.data.length; i++) {
            let purchaseItem = result.data[i]
            if (purchaseItem.termNo == 1
              || purchaseItem.termNo == 2
              || purchaseItem.termNo == 3
              || purchaseItem.termNo == 5
              || purchaseItem.termNo == 14
              || purchaseItem.termNo == 15
            ) {
              this.formDocumentTypeData.push({
                model: purchaseItem.id,
                label: purchaseItem.termName
              })
            }
          }
          if (this.crossStatus == 2 || this.crossStatus == 1) {
            this.formDocumentTypeData.push({
              model: '978108623924236290',
              label: '鄂技协'
            })
            this.formDocumentTypeData.push({
              model: '978108532228362241',
              label: '鄂技协纪要'
            })
          }
          //判断专人选择专项文种
          if (role.toString().indexOf('办公室主任') > -1 || role.toString().indexOf('人事专员') > -1) {
            this.formDocumentTypeData.push({
              model: '978255291938586740',
              label: '鄂技交办公会议纪要'
            })
          }
          if (role.toString().indexOf('人事主管') > -1 || role.toString().indexOf('人事专员') > -1) {
            this.formDocumentTypeData.push({
              model: '976656351180701697',
              label: '鄂技交党总支部会议纪要'
            })
          }
          if (role.toString().indexOf('党建专员') > -1) {
            this.formDocumentTypeData.push({
              model: '976656222025498625',
              label: '鄂技交党'
            })
          }
          if (role.toString().indexOf('财务专员') > -1) {
            this.formDocumentTypeData.push({
              model: '976656179017105409',
              label: '鄂技交财'
            })
            this.formDocumentTypeData.push({
              model: '976656079536603137',
              label: '鄂技交人'
            })
          }
          if (role.toString().indexOf('工会干事') > -1) {
            this.formDocumentTypeData.push({
              model: '976656401982111746',
              label: '鄂技交工'
            })
          }
          if (role.toString().indexOf('纪检') > -1) {
            this.formDocumentTypeData.push({
              model: '976656263691714561',
              label: '鄂技交纪'
            })
          }
          console.log(this.formDocumentTypeData)
        } else {
          this.$message.error(result.msg)
        }
      })
    },
    //获取文本编号
    getDocumentCode () {
      let param = {
        path: {
          id: this.formModel.CategoryID
        }
      }
      this.loadingJudgeData.operationDone = false
      Api.Administration.getDocumentCode(param).then((result) => {
        this.loadingJudgeData.operationDone = true
        if (this.formModel.CategoryID == '978255291938586738') {
          this.formModel.receiveNum = '无文号'
        } else {
          if (result.status === 0) {
            this.formModel.receiveNum = result.data
            this.initFormSchema()
          } else {
            this.$message.error(result.msg)
          }
        }

      })
    },
    //根据会签部门自动获取会签人（部门主任）
    getSignedMember () {
      if ($.inArray(this.draftDeptId, this.formModel.signedDepts) < 0) {
        this.formModel.signedDepts.splice(0, 0, this.draftDeptId)
      }
      let signedsData = (this.formModel.signedDepts || []).join(',')
      this.formMissionMemberData.splice(0, this.formMissionMemberData.length)
      Api.PersonnelManagement.personLeaderMember(signedsData).then((result) => {
        if (result.status === 0) {
          for (let member of result.data) {
            if ($.inArray(member.personName, this.formMissionMemberData) >= 0) {
              continue
            }
            this.formMissionMemberData.push(member.personName)
          }
          this.formModel.signedPerson = this.formMissionMemberData.join('，')
//            this.initFormSchema();
        }
      })
    },
    //选择是否带任务后刷新界面
    radioValueChanged () {
      this.initFormSchema()
    },
    //选择自有发文后显示发文类型
    selectorValueChanged (model) {
      if (model === 'contentClass') {
        this.initFormSchema()
      }
      if (model === 'CategoryID') {
        let categoryItem = this.formDocumentTypeData.find(item => item.model == this.formModel.CategoryID)
        if (categoryItem) {
          if (categoryItem.label == '其他') {
            return
          }
        }
        this.getDocumentCode()
      }
      if (model === 'signedDepts') {
        this.getSignedMember()
      }
    },
    //多选级联下拉框值传值
    cascaderMultipleValueChanged (model) {
      this.formCustomizePeopleData = model
    },
    //表单验证
    formValidate () {
      return this.$refs.childrenForm.validate()
    },
    //清空表单
    formResetFields () {
      this.formFileData = []
      this.$refs.childrenForm.resetFields()
      this.initFormSchema()
      this.formPeopleWeightData = []
    },

    //取消提交
    formCancel () {
      this.formResetFields()
    },
    //表单提交
    formSubmit (data) {
      this.$refs.childrenForm.letTextEditorSubmit()
      let ext = {}
      $.extend(true, ext, this.formModel)
      let membersList = []
      for (let i = 0; i < this.formPeopleWeightData.length; i++) {
        membersList.push(this.formPeopleWeightData[i].model)
      }
      ext.membersList = membersList
      let feesList = []
      let projectParentId = ''
      if (this.projectStep === 'apply') {
        projectParentId = ''
      } else {
        projectParentId = this.formModel.projectId
      }
      ext.feesList = feesList
      ext.applyDate = moment(ext.applyDate).format('YYYY-MM-DD')
      ext.endDate = moment(ext.endDate).format('YYYY-MM-DD')
      ext.applyFileData = this.formApplyFileData
      ext.executeFileData = this.formExecuteFileData
      ext.checkFileData = this.formCheckFileData
      let param = {
        data: {
          projectInfoReq: {
            projectCategory: 'init',
            projectStep: 'init',
            draftDeptId: this.formModel.draftDeptId,
            projectName: this.formModel.projectName,
            projectNo: this.formModel.projectNo,
            projectParentId: projectParentId,
            description: this.formModel.description,
            ext: ext,
          },
          // 考核集合
          membersList: membersList,
          // 获取项目负责人ID
        }

      }
      $.extend(true, param, this.formModel)
      param.membersList = membersList
      param['ext'] = {
        membersList: param.membersList,
        // projectManagerData: this.formModel.projectManagerData,
        draftMan: param.draftMan,
        draftDeptName: param.draftDeptName,
        projectName: param.projectName,
        copying: param.copying,
        cC: param.cC,
        difficultyFactor: param.difficultyFactor,
        isSigned: param.isSigned,
        signedDepts: param.signedDepts,
        executeDepts: param.executeDepts,
        signedPerson: param.signedPerson,
        // nuclearMan: param.nuclearMan,
        openRange: param.openRange,
        // permissions: param.permissions,
        permissionsPeople: this.formCustomizePeopleData,
        // contentClass: param.contentClass,
        // imprintNum: param.imprintNum,
        imprintDate: moment(param.imprintDate).format('YYYY-MM-DD HH:mm:ss'),
        // CategoryID: param.CategoryID,
        receiveNum: param.receiveNum,
        gross: param.gross,
        budget: param.budget,
        scheme: param.scheme,
        goal: param.goal,
        isTask: false,
        year: param.year,
        fileData: this.formFileData,
        documentType: param.documentType,
        // budgetRate: param.budgetRate,
        // contRate: param.contRate
      }
//        return false;
      this.loadingJudgeData.operationDone = false
      console.log('param', param)
      Api.ProjectManagements.addWeeklyList(param).then((result) => {
        this.loadingJudgeData.operationDone = true
        if (result.status === 0) {
          this.$message({
            type: 'success',
            message: '新增成功!'
          })
          this.$router.go(-1)
        } else {
          this.$message.error(result.data)
        }
      })
    },
    //递归组装级联选择器数据源
    assembleOrgData (source) {
      let dest = []
      for (let i = 0; i < source.length; i++) {
        let org = {
          value: source[i].id,
          label: source[i].name
        }
        if (source[i].childList && source[i].childList.length > 0) {
          org['children'] = this.assembleOrgData(source[i].childList)
        }
        dest.push(org)
      }
      return dest
    },

    setCascaderMultipleValue (value) {
//        this.formCustomizePeopleData = [];  //清空级联选择器选中值
      let extOptionChildrens = this.formPermissionsData.find(item => item.value == value[0]).children
      let checkV = extOptionChildrens.find(item => item.value == value[1])
      let checkInclude = this.formModel.permissionsPeople.find(item => item.value == value[1])
      if (!checkInclude) {
        this.formModel.permissionsPeople.push(checkV)
        this.formCustomizePeopleData.push(value[value.length - 1])
      }
    },

    handleClose (model) {
      this.formModel.permissionsPeople.find((item, index) => {
        if (item.value === model.value) {
          this.formModel.permissionsPeople.splice(index, 1)
          this.formCustomizePeopleData.splice(index, 1)
          this.initFormSchema()
          return true
        }
      })
    },

  },
  components: {
    PageLoading, DataForm
  }
}
</script>

<style scoped lang="less" rel="stylesheet/less">
.expand-right {
  @media (min-width: 768px) {
    padding-left: 0 !important;
  }
}

.page-content {
  padding: 15px;
}
</style>
