<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">{{title}}</h1>
      <!--Searchbox-->
      <!--<div class="searchbox">-->
      <!--<div class="input-group custom-search-form">-->
      <!--<input type="text" class="form-control" placeholder="Search..">-->
      <!--<span class="input-group-btn">-->
      <!--<button class="text-muted" type="button"><i class="demo-pli-magnifi-glass"></i></button>-->
      <!--</span>-->
      <!--</div>-->
      <!--</div>-->
    </div>
    <!--End page title-->

    <!--Breadcrumb-->
    <!--<ol class="breadcrumb">-->
    <!--<li><a href="#">Home</a></li>-->
    <!--<li><a href="#">Layouts</a></li>-->
    <!--<li class="active">Demo</li>-->
    <!--</ol>-->
    <!--End breadcrumb-->

    <!--Page content-->
    <div class="page-content">
      <div class="panel">
        <div class="panel-body">
          <div class="panel-body" style="padding-bottom: 10px" v-if="!checkOrVerify && !verifyDone">
            <verify-button
              :canOnlyDestroy="isReject"
              :taskId="taskId"
            >
            </verify-button>
          </div>
          <data-form
            :title="formTitle"
            :btnTitle="formBtnTitle"
            showCancelBtn="false"
            :schema="formSchema"
            :model="formModel"
            :showTitle="false"
            :btnData="formBtnData"
            ref="childrenForm"
            @selectorValueChanged="selectorValueChanged"
            @radioValueChanged="radioValueChanged"
            @dynamicValueChanged="dynamicValueChanged"
          >
          </data-form>
          <log-data-table
            :logOperationData="logOperationData"
            :formModel="formModel"
            :logOperationDataExp="logOperationDataExp"
            :tableClumnsData="formSchema"
            ref="logChildren"
          ></log-data-table>
          <flow-record-table
            :checkOrVerify="checkOrVerify"
            :flowId="flowId"
          >
          </flow-record-table>
        </div>
      </div>
    </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 FlowRecordTable from '../../components/FlowRecordTable.vue'
  import VerifyButton from '../../components/verifyButton.vue'
  import Api from '../../server/index.js'
  import {baseUrl} from '../../config/env.js';
  import {getItem} from '../../config/mUtils.js'
  import LogDataTable from "../../components/LogDataTable";

  export default {
    beforeRouteEnter(to, from, next) {
      next(function (vm) {
        global.getMenuIndex(vm);
      })
    },
    data() {
      return {
        expandRight: false,
        title: '',
        projectType: '',
        projectStep: '',
        checkOrVerify: true, //标识是查看详情还是审批
        verifyDone: false, //标识是否审批完成
        canEdit: false, //标识是否能编辑
        loadingJudgeData: { //加载圈是否隐藏的判断数据源
          coreDataDone: false,
          peopleDataDone: false,
          orgDataDone: false,
          projectDataDone: false
        },
        //form表单数据源
        formType: "add", //标识当前form是新增还是编辑：add：新增；edit：编辑
        formTitle: "",
        formBtnTitle: "返回",
        formSchema: [],
        formModel: {},
        formBtnData: [],
        formPeopleData: [], //人数据源
        formOrgData: [], //使用部门的数据源
        formProjectData: [], //可选择项目的数据源
        formFileData: [], //文件列表
        formPeopleWeightData: [], //员工权重数据源
        formFeesData: [], //执行费用数据源
        formFeesTypeData: [ //执行费用类型的数据源
          {
            label: '使用',
            model: 'use'
          },
          {
            label: '收入',
            model: 'earn'
          },
        ],
        formCheckTypeData: [ //是否正常验收数据源
          {
            label: '否',
            value: false
          },
          {
            label: '是',
            value: true
          },
        ],
        formDelayData: [ //是否延期数据源
          {
            label: '否',
            value: false
          },
          {
            label: '是',
            value: true
          },
        ],
        formProjectManagerData: [],  //项目负责人数据源
        //表单文件上传相关数据源
        formApplyFileData: [], //附件数据源
        formVerifyFileData: [],
        formExecuteFileData: [],
        formCheckFileData: [],
        fileListData: [],
        //流程审批相关数据源
        isReject: false,//标识是否是驳回状态（对于驳回的申请在审批列表只能进行作废操作）
        taskId: '',
        flowId: '',
        hasSubmit: true,//是否已经提交申请
        showDetail: false,//是否是点击查看详情过来的


        //操作日志表
        logOperationData: {},
        logOperationDataExp: {
          tablePrimarykey: this.$route.params.id,
          tableName: 'project_info',
          operatorType: 'projectLog',
          operatorId: getItem("userInfoId"),
        },
      }
    },
    created() {
      console.log(getItem("userInfoId"))
      if (this.$route.name.indexOf('Detail') !== -1) {
        this.projectType = this.$route.meta.type;
        this.projectStep = this.$route.meta.step;
        this.flowId = this.$route.params.id;
        switch (this.projectType) {
          case 'portrait':
            switch (this.projectStep) {
              case 'apply':
                this.title = '纵向项目申报';

                break;
              // case 'verify':
              //   this.title = '纵向项目评审';
              //
              //   break;
              case 'execute':
                this.title = '纵向项目执行';

                break;
              case 'check':
                this.title = '纵向项目验收';

                break;
            }
            break;
          case 'market':
            switch (this.projectStep) {
              case 'apply':
                this.title = '市场项目申报';

                break;
              case 'execute':
                this.title = '市场项目执行';

                break;
              case 'check':
                this.title = '市场项目验收';

                break;
            }
            break;
          case 'internal':
            switch (this.projectStep) {
              case 'apply':
                this.title = '内部项目申报';

                break;
              case 'execute':
                this.title = '内部项目执行';

                break;
              case 'check':
                this.title = '内部项目验收';

                break;
            }
            break;
        }
      }
      if (this.$route.name === 'ProjectVerify') {
        this.projectType = this.$route.params.type;
        this.projectStep = this.$route.params.step;
        this.taskId = this.$route.params.taskId;
        this.flowId = this.$route.params.verifyId;
        this.checkOrVerify = false;
        this.verifyDone = (this.$route.query.isNotVerifyReady === 'N');
        switch (this.projectType) {
          case 'portrait':
            switch (this.projectStep) {
              case 'apply':
                this.title = '纵向项目申报';

                break;
              // case 'verify':
              //   this.title = '纵向项目评审';
              //
              //   break;
              case 'execute':
                this.title = '纵向项目执行';

                break;
              case 'check':
                this.title = '纵向项目验收';
                break;
            }
            break;
          case 'market':
            switch (this.projectStep) {
              case 'apply':
                this.title = '市场项目申报';

                break;
              case 'execute':
                this.title = '市场项目执行';

                break;
              case 'check':
                this.title = '市场项目验收';

                break;
            }
            break;
          case 'internal':
            switch (this.projectStep) {
              case 'apply':
                this.title = '内部项目申报';

                break;
              case 'execute':
                this.title = '内部项目执行';

                break;
              case 'check':
                this.title = '内部项目验收';

                break;
            }
            break;
        }
      }
      if (this.$route.name === 'ProjectArchive') {
        this.projectType = this.$route.params.type;
        this.projectStep = this.$route.params.step;
        this.flowId = this.$route.params.id;
        switch (this.projectType) {
          case 'portrait':
            switch (this.projectStep) {
              case 'apply':
                this.title = '纵向项目申报';

                break;
              // case 'verify':
              //   this.title = '纵向项目评审';
              //
              //   break;
              case 'execute':
                this.title = '纵向项目执行';

                break;
              case 'check':
                this.title = '纵向项目验收';

                break;
            }
            break;
          case 'market':
            switch (this.projectStep) {
              case 'apply':
                this.title = '市场项目申报';

                break;
              case 'execute':
                this.title = '市场项目执行';

                break;
              case 'check':
                this.title = '市场项目验收';

                break;
            }
            break;
          case 'internal':
            switch (this.projectStep) {
              case 'apply':
                this.title = '内部项目申报';

                break;
              case 'execute':
                this.title = '内部项目执行';

                break;
              case 'check':
                this.title = '内部项目验收';

                break;
            }
            break;
        }
      }
      this.initFormBtn();
      this.initFormData();
      this.initFormSchema();
      this.getProjectDetail();
      this.getAvailableProject();
      this.getAllPeople();
      this.getOrganization();
    },
    watch: {
      formPeopleData() {
        this.initFormSchema();
      },
      formOrgData() {
        this.initFormSchema();
      },
      canEdit() {
        this.initFormBtn();
      },
    },
    computed: {
      //判断加载圈是否能隐藏
      pageLoading() {
        if (this.projectStep === 'apply') {
          return !(this.loadingJudgeData.coreDataDone && this.loadingJudgeData.peopleDataDone && this.loadingJudgeData.orgDataDone);
        } else {
          return !(this.loadingJudgeData.coreDataDone && this.loadingJudgeData.peopleDataDone && this.loadingJudgeData.orgDataDone && this.loadingJudgeData.projectDataDone);
        }
      }
    },
    methods: {
      //初始化表单数据源
      //初始化form btn
      initFormBtn() {
        if (this.checkOrVerify) {
          if (this.showDetail && !this.canEdit) {
            this.formBtnData = [
              {
                title: '返回',
                type: 'primary',
                callback: () => {
                  //返回
                  this.$router.go(-1);
                }
              },
            ];
          } else {
            if ((this.projectStep === 'execute' || this.projectStep === 'check') && !this.hasSubmit) {
              this.formBtnData = [
                {
                  title: '保存',
                  type: 'primary',
                  callback: () => {
                    if (this.formValidate() && this.judgeProjectMemberInfo(true)) {
                      this.editProjectApply();
                    }
                  }
                },
                {
                  title: '提交审批',
                  type: 'primary',
                  callback: () => {
                    if (this.formValidate() && this.judgeProjectMemberInfo(true)) {
                      this.$confirm('是否要提交审批，提交后不可编辑', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                      }).then(() => {
                        this.submitProjectApplyToVerify();
                      }).catch(() => {

                      });
                    }
                  }
                },
                {
                  title: '返回',
                  type: 'primary',
                  callback: () => {
                    //关闭返回
                    this.$router.go(-1);
                  }
                }
              ];
            } else {
              if (!this.canEdit) {
                console.log(this.canEdit);
                this.formBtnData = [
                  {
                    title: '返回',
                    type: 'primary',
                    callback: () => {
                      //返回
                      this.$router.go(-1);
                    }
                  },
                ];
              } else {
                this.formBtnData = [
                  {
                    title: '确定修改',
                    type: 'primary',
                    callback: () => {
                      if (this.formValidate() && this.judgeProjectMemberInfo(true)) {
                        this.editProjectApply();
                      }
                    }
                  },
                ];
              }
            }
          }
        } else {
          this.formBtnData = [
            {
              title: '返回',
              type: 'primary',
              callback: () => {
                //返回
                this.$router.go(-1);
              }
            },
          ];
        }
      },
      initFormData() {
//          description (string, optional): 备注 ,
//          ext (inline_model_31, optional): 详细内容 ,
//          projectCategory (string, optional): 项目类别 ：internal内部项目 longitudinal纵向项目 market市场项目 ,
//          projectName (string, optional): 项目名称 ,
//          projectNo (string, optional): 项目编号 ,
//          projectParentId (integer, optional): 用于保存评审 执行 验收的项目编号 ,
//          projectStep (string, optional): 项目步骤 declare申报 review评审 execute执行 accepting验收

//          accept (boolean, optional): 验收 ,
//          acceptUrl (string, optional): 验收资料 ,
//          acceptingRemark (string, optional): 验收备注 ,
//          annexUrl (string, optional): 附件链接 ,
//          applyDate (string, optional): 申请时间 ,
//          budget (string, optional): 项目预算 ,
//          declareRemark (string, optional): 申报备注 ,
//          endDate (string, optional): 项目截止时间 ,
//          executeRemark (string, optional): 执行备注 ,
//          extension (boolean, optional): 是否延期 ,
//          extensionDate (string, optional): 延期截止时间 ,
//          feesList (Array[ProjectRegistrationFees], optional): 费用登记 ,
//          feesUrl (string, optional): 费用材料 ,
//          financeOpinions (string, optional): 财务意见 ,
//          instruction (string, optional): 项目说明 ,
//          membersList (Array[ProjectMembers], optional): 项目成员 ,
//          revenue (string, optional): 项目预计收入 ,
//          reviewOpinions (string, optional): 评审意见 ,
//          reviewRemark (string, optional): 评审备注

        switch (this.projectStep) {
          case 'apply':
            this.formModel = {
              projectName: '',
              projectNo: '',
              applyDate: '',
              endDate: '',
              projectManagerData: [],
              membersList: [],
              budget: '',
              revenue: '',
              instruction: '',
              description: '',
              applyFileData: [],
              //进度条
              step: 1,
              annotation: '',
            };
            break;
          case 'execute':
            this.formModel = {
              projectName: '',
              projectNo: '',
              applyDate: '',
              endDate: '',
              projectManagerData: [],
              membersList: [],
              budget: '',
              revenue: '',
              instruction: '',
              description: '',
              applyFileData: [],
              reviewOpinions: '',
              reviewRemark: '',
              feesList: '',
              executeRemark: '',
              executeFileData: [],
              projectParentId: '',
              annotation: '',
            };
            break;
          case 'check':
            this.formModel = {
              projectName: '',
              projectNo: '',
              applyDate: '',
              endDate: '',
              projectManagerData: [],
              membersList: [],
              budget: '',
              revenue: '',
              instruction: '',
              description: '',
              applyFileData: [],
              reviewOpinions: '',
              reviewRemark: '',
              executeRemark: '',
              executeFileData: [],
              accept: true,
              extension: false,
              extensionDate: '',
              acceptingRemark: '',
              checkFileData: [],
              projectParentId: '',
              annotation: '',
            };
            break;
        }
      },
      //判断form字段是否可以编辑
      judgeFormEditable(step) {
        // debugger
        console.log("this.canEdit:", this.canEdit);
        if (this.$route.name.indexOf('EditDetail') !== -1) {
          this.hasSubmit = false;
          return true;
        } else {
          this.hasSubmit = true;
          return this.canEdit;
        }
        // if (this.$route.name.indexOf('EditDetail') == -1 && this.$route.name.indexOf('AcceptDetail') == -1 && !this.canEdit) {
        //   this.showDetail = true;
        //   return false;
        // } else {
        //   if (step === 'execute') {
        //     if (this.$route.name.indexOf('AcceptDetail') !== -1) {
        //       return false;
        //     } else {
        //       return (this.$route.name.indexOf('Detail') !== -1 && !this.hasSubmit);
        //     }
        //   } else if (step === 'apply') {
        //     if (this.$route.name.indexOf('EditDetail') !== -1) {
        //       return true;
        //     }
        //   } else {
        //     return (this.canEdit && this.projectStep === step);
        //   }
        // }
      },
      //验收时修改权重
      judgeEditWeight(step) {
        if (this.$route.name.indexOf('AcceptDetail') !== -1 || (this.$route.name.indexOf('ApplyDetail') !== -1 && this.canEdit)) {
          return true;
        } else {
          if (this.$route.name.indexOf('EditDetail') !== -1) {
            return true;
          } else {
            console.log("this.$route.name", this.$route.name);
            this.judgeFormEditable(step);
          }
        }
      },
      //组装项目申请form schema
      assembleApplySchema() {
        this.formSchema = [
          {
            type: "custome-steps",
            title: '审批状态',
            model: 'step',
            dataType: 'Number',
            activie: this.formModel.step,
            externalValue: {}
          },
          {
            type: "custom-input",
            title: '项目名称',
            model: 'projectName',
            rules: [
              {required: true, message: '项目名称不能为空'}
            ],
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
            }
          },
          {
            type: "custom-input",
            title: '项目编号',
            model: 'projectNo',
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
            }
          },
          {
            type: "custom-date-picker",
            title: '申请时间',
            model: 'applyDate',
            externalValue: {
              disabled: true,
              dateFormat: 'yyyy-MM-dd'
            }
          },
          {
            type: "custom-date-picker",
            title: '项目截止日期',
            model: 'endDate',
            rules: [
              {required: true, message: '项目截止日期不能为空'}
            ],
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
              dateFormat: 'yyyy-MM-dd',
              pickerOptions: {
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7;
                }
              }
            }
          },
          {
            type: "custom-cascader",
            title: '项目负责人',
            model: 'projectManagerData',
            rules: [
              {required: true, message: '项目负责人不能为空'}
            ],
            externalValue: {
              disabled: true,
              options: this.formProjectManagerData
            }
          },
          {
            type: "custom-dynamic",
            title: '添加成员',
            model: 'membersList',
            rules: [
              {required: true, message: '成员不能为空'}
            ],
            externalValue: {
              disabled: true,
              btnData: {
                title: '新增',
                externalValue: {
                  disabled: true,
                },
                callback: () => {
                  this.formPeopleWeightData.push(
                    {
                      span: 24,
                      model: {
                        id: [],
                        weight: '',
                        jobContent: '',
                      },
                      schema: [
                        {
                          type: "custom-cascader",
                          title: '员工',
                          model: 'id',
                          span: 7,
                          rules: [
                            {required: true, message: '员工不能为空'}
                          ],
                          externalValue: {
                            disabled: true,
                            multiple: false,
                            options: this.formPeopleData
                          }
                        },
                        {
                          type: "custom-input-number",
                          title: '权重',
                          model: 'weight',
                          span: 7,
                          rules: [
                            {required: true, message: '权重不能为空'},
                            {type: 'number', message: '权重必须为数字值'}
                          ],
                          externalValue: {
                            disabled: !this.judgeEditWeight('apply'),
                          }
                        },
                        {
                          type: "custom-input",
                          title: '工作内容',
                          model: 'jobContent',
                          span: 7,
                          externalValue: {
                            disabled: !this.judgeFormEditable('apply'),
                          }
                        },
                        {
                          type: 'delete',
                          externalValue: {
                            disabled: true,
                          },
                          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: "custom-input-number",
            title: '项目预算(/元)',
            model: 'budget',
            rules: [
              {required: true, message: '项目预算不能为空'},
              {type: 'number', message: '项目预算必须为数字值'}
            ],
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
            }
          },
          {
            type: "custom-input-number",
            title: '项目预计收益(/元)',
            model: 'revenue',
            rules: [
              {type: 'number', message: '项目预计收益必须为数字值'}
            ],
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
            }
          },
          {
            type: "custom-textarea",
            title: '项目说明',
            model: 'instruction',
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
            }
          },
          {
            type: "custom-textarea",
            title: '备注',
            model: 'description',
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
            }
          },
          {
            type: "custom-upload-file",
            title: '申报-附件',
            model: 'applyFileData',
            externalValue: {
              disabled: !this.judgeFormEditable('apply'),
              name: 'file',
              actionUrl: `${baseUrl}/api/common/file-upload`,
              requestHeader: {},
              requestData: {},
              uploadFileSuccess: (response, file, fileList) => {
                if (response.status === 0) {
                  this.formApplyFileData.push({
                    id: file.uid,
                    name: file.name + "-" + getItem("userName") + "-" + getItem("orgNameStr"),
                    url: baseUrl + response.data.url
                  });
                  this.initFormSchema();
                } else {
                  this.$message.error(response.msg);
                }
              },
              uploadFilePreview: (file) => {
                window.open(file.url, '_blank');
              },
              uploadFileRemove: (file, fileList) => {
                for (let i = 0; i < this.formApplyFileData.length; i++) {
                  if (file.uid === this.formApplyFileData[i].uid) {
                    this.formApplyFileData.splice(i, 1);
                    break;
                  }
                }
                this.initFormSchema();
              },
              fileList: this.formApplyFileData
            }
          },
          {
            type: 'submit'
          }
        ];
      },
      //组装项目评审form schema
      // assembleVerifySchema(){
      //   this.formSchema.pop();
      //   let applyData = [
      //     {
      //       type: "custom-textarea",
      //       title: '评审意见',
      //       model: 'reviewOpinions',
      //       externalValue: {
      //         disabled: !this.judgeFormEditable('verify'),
      //       }
      //     },
      //     {
      //       type: 'submit'
      //     }
      //   ];
      //   for (let i = 0; i < applyData.length; i++) {
      //     this.formSchema.push(applyData[i]);
      //   }
      // },
      //组装项目执行form schema
      assembleExecuteSchema() {
        this.formSchema.pop();
        let executeData = [
          {
            type: "custom-dynamic",
            title: '费用登记',
            model: 'feesList',
            externalValue: {
              disabled: !this.judgeFormEditable('execute'),
              index: this.fileListData.length,
              btnData: {
                title: '新增',
                callback: (index) => {
                  this.fileListData.push([]);
                  this.formFeesData.push(
                    {
                      span: 24,
                      model: {
                        detailed: '',
                        amount: '',
                        description: '',
                        executeCostFileData: [],
                      },
                      schema: [
                        // {
                        //   type: "custom-selector",
                        //   title: '类型',
                        //   model: 'category',
                        //   span: 7,
                        //   rules: [
                        //     {required: true, message: '费用类型不能为空'},
                        //   ],
                        //   externalValue: {
                        //     disabled: !this.judgeFormEditable('execute'),
                        //     multiple: false,
                        //     options: this.formFeesTypeData
                        //   }
                        // },
                        {
                          type: "custom-input",
                          title: '明细',
                          model: 'detailed',
                          span: 5,
                          externalValue: {
                            disabled: !this.judgeFormEditable('execute'),
                          }
                        },
                        {
                          type: "custom-input-number",
                          title: '金额',
                          model: 'amount',
                          span: 5,
                          rules: [
                            {required: true, message: '费用金额不能为空'},
                            {type: 'number', message: '费用金额必须为数字值'}
                          ],
                          externalValue: {
                            disabled: !this.judgeFormEditable('execute'),
                          }
                        },
                        {
                          type: "custom-input",
                          title: '备注',
                          model: 'description',
                          span: 5,
                          externalValue: {
                            disabled: !this.judgeFormEditable('execute'),
                          }
                        },
                        {
                          type: "custom-upload-file",
                          title: '费用单据',
                          model: 'executeCostFileData',
                          span: 5,
                          externalValue: {
                            disabled: !this.judgeFormEditable('execute'),
                            name: 'file',
                            actionUrl: `${baseUrl}/api/common/file-upload`,
                            requestHeader: {},
                            requestData: {},
                            uploadFileSuccess: (response, file, fileList) => {
                              if (response.status === 0) {
                                this.fileListData[index].push({
                                  id: file.uid,
                                  name: file.name + "-" + getItem("userName") + "-" + getItem("orgNameStr"),
                                  url: baseUrl + response.data.url
                                });
                                this.initFormSchema();
                              } else {
                                this.$message.error(response.msg);
                              }
                            },
                            uploadFilePreview: (file) => {
                              window.open(file.url, '_blank');
                            },
                            uploadFileRemove: (file, fileList) => {
                              for (let i = 0; i < this.fileListData[index].length; i++) {
                                if (file.uid === this.fileListData[index][i].uid) {
                                  this.fileListData[index].splice(i, 1);
                                  break;
                                }
                              }
                              this.initFormSchema();
                            },
                            fileList: this.fileListData[index]
                          }
                        },
                        {
                          type: 'delete',
                          callback: (deleteIndex) => {
                            this.fileListData.splice(deleteIndex, 1);
                            this.formFeesData.splice(deleteIndex, 1);
                            this.formModel.feesList = this.formFeesData;
                            this.initFormSchema();
                          }
                        },
                      ],
                    },
                  );
                  this.formModel.feesList = this.formFeesData;
                  this.initFormSchema();
                }
              },
              dynamicData: this.formFeesData
            }
          },
          {
            type: "custom-textarea",
            title: '执行说明',
            model: 'executeRemark',
            externalValue: {
              disabled: !this.judgeFormEditable('execute'),
            }
          },
          {
            type: "custom-upload-file",
            title: '执行-附件',
            model: 'executeFileData',
            externalValue: {
              disabled: !this.judgeFormEditable('execute'),
              name: 'file',
              actionUrl: `${baseUrl}/api/common/file-upload`,
              requestHeader: {},
              requestData: {},
              uploadFileSuccess: (response, file, fileList) => {
                if (response.status === 0) {
                  this.formExecuteFileData.push({
                    id: file.uid,
                    name: file.name + "-" + getItem("userName") + "-" + getItem("orgNameStr"),
                    url: baseUrl + response.data.url
                  });
                  this.initFormSchema();
                } else {
                  this.$message.error(response.msg);
                }
              },
              uploadFilePreview: (file) => {
                window.open(file.url, '_blank');
              },
              uploadFileRemove: (file, fileList) => {
                for (let i = 0; i < this.formExecuteFileData.length; i++) {
                  if (file.uid === this.formExecuteFileData[i].uid) {
                    this.formExecuteFileData.splice(i, 1);
                    break;
                  }
                }
                this.initFormSchema();
              },
              fileList: this.formExecuteFileData
            }
          },
          {
            type: 'submit'
          }
        ];
        for (let i = 0; i < executeData.length; i++) {
          this.formSchema.push(executeData[i]);
        }
      },
      //组装项目验收form schema
      assembleCheckSchema() {
        this.formSchema.pop();
        let checkData = [
          {
            type: "custom-radio",
            title: '是否正常验收',
            model: 'accept',
            externalValue: {
              disabled: !this.judgeFormEditable('check'),
              options: this.formCheckTypeData
            }
          },
          {
            type: "custom-radio",
            title: '延期(限期整改)',
            model: 'extension',
            externalValue: {
              disabled: !this.judgeFormEditable('check'),
              options: this.formDelayData
            }
          },
          {
            type: "custom-date-picker",
            title: '整改截止时间',
            model: 'extensionDate',
            hide: !this.formModel.extension,
            rules: [
              {required: true, message: '整改截止时间不能为空'}
            ],
            externalValue: {
              disabled: !this.judgeFormEditable('check'),
              dateFormat: 'yyyy-MM-dd',
              pickerOptions: {
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7;
                }
              }
            }
          },
          {
            type: "custom-textarea",
            title: '验收说明',
            model: 'acceptingRemark',
            externalValue: {
              disabled: !this.judgeFormEditable('check'),
            }
          },
          {
            type: "custom-upload-file",
            title: '验收-附件',
            model: 'checkFileData',
            externalValue: {
              disabled: !this.judgeFormEditable('check'),
              name: 'file',
              actionUrl: `${baseUrl}/api/common/file-upload`,
              requestHeader: {},
              requestData: {},
              uploadFileSuccess: (response, file, fileList) => {
                if (response.status === 0) {
                  this.formCheckFileData.push({
                    id: file.uid,
                    name: file.name + "-" + getItem("userName") + "-" + getItem("orgNameStr"),
                    url: baseUrl + response.data.url
                  });
                  this.initFormSchema();
                } else {
                  this.$message.error(response.msg);
                }
              },
              uploadFilePreview: (file) => {
                window.open(file.url, '_blank');
              },
              uploadFileRemove: (file, fileList) => {
                for (let i = 0; i < this.formCheckFileData.length; i++) {
                  if (file.uid === this.formCheckFileData[i].uid) {
                    this.formCheckFileData.splice(i, 1);
                    break;
                  }
                }
                this.initFormSchema();
              },
              fileList: this.formCheckFileData
            }
          },
          {
            type: 'submit'
          }
        ];
        for (let i = 0; i < checkData.length; i++) {
          this.formSchema.push(checkData[i]);
        }
      },
      //初始化form schema
      initFormSchema() {
        switch (this.projectType) {
          case 'portrait':
            switch (this.projectStep) {
              case 'apply':
                this.assembleApplySchema();
                break;
              case 'execute':
                this.assembleApplySchema();
                this.assembleExecuteSchema();
                break;
              case 'check':
                this.assembleApplySchema();
                this.assembleExecuteSchema();
                this.assembleCheckSchema();
                break;
            }
            break;
          case 'market':
            switch (this.projectStep) {
              case 'apply':
                this.assembleApplySchema();
                break;
              case 'execute':
                this.assembleApplySchema();
                this.assembleExecuteSchema();
                break;
              case 'check':
                this.assembleApplySchema();
                this.assembleExecuteSchema();
                this.assembleCheckSchema();
                break;
            }
            break;
          case 'internal':
            switch (this.projectStep) {
              case 'apply':
                this.assembleApplySchema();
                break;
              case 'execute':
                this.assembleApplySchema();
                this.assembleExecuteSchema();
                break;
              case 'check':
                this.assembleApplySchema();
                this.assembleExecuteSchema();
                this.assembleCheckSchema();
                break;
            }
            break;
        }
        this.formSchema.splice(this.formSchema.length - 1, 0,
          {
            type: "custom-input",
            title: '所长批注',
            hide: this.formModel.annotation ? false : true,
            model: 'annotation',
            externalValue:
              {
                disabled: true
              }
          },
        )
      },
      //获取项目详情
      getProjectDetail() {
        let param = {
          path: {
            id: this.$route.params.id
          },
        };
        Api.ProjectManagement.getProjectDetail(param).then((result) => {
          console.log("result--", result);
          console.log("this.$route.name--", this.$route.name);
          this.loadingJudgeData.coreDataDone = true;
          if (result.status === 0) {
            if (this.$route.name.indexOf('Detail') !== -1) {
              // const userId = getItem("userId");
              // if (result.data.isEdit && userId === result.data.createdBy) {
              //   this.canEdit = true;
              // }
              console.log("result.data.isBack:", result.data.isBack);
              if (result.data.isBack) {
                this.canEdit = true;
                this.activitiFrom = 'restart';
                // this.rewriteAgreeVerify = true;
              } else {
                this.canEdit = false;
              }
            } else if (this.$route.name === 'ProjectVerify') {
              // this.isReject = result.data.isEdit;
              this.isReject = result.data.isBack;
              this.cannotEdit = !result.data.isEdit;
              // this.rewriteAgreeVerify = result.data.isEdit;
              this.activitiFrom = 'commit';
            }
            this.hasSubmit = result.data.isWorkFlows;
            let project = {};
            $.extend(true, project, result.data.ext);
            project['projectId'] = result.data.id;
            project.applyDate = moment(project.applyDate).format('YYYY-MM-DD');
            project.endDate = moment(project.endDate).format('YYYY-MM-DD');
            if (project.membersList) {
              this.formPeopleWeightData = [];
              for (let i = 0; i < project.membersList.length; i++) {
                this.formPeopleWeightData.push(
                  {
                    span: 24,
                    model: {
                      id: project.membersList[i].id,
                      weight: project.membersList[i].weight,
                      jobContent: project.membersList[i].jobContent,
                    },
                    schema: [
                      {
                        type: "custom-cascader",
                        title: '员工',
                        model: 'id',
                        span: 7,
                        rules: [
                          {required: true, message: '员工不能为空'}
                        ],
                        externalValue: {
                          disabled: true,
                          multiple: false,
                          options: this.formPeopleData
                        }
                      },
                      {
                        type: "custom-input-number",
                        title: '权重',
                        model: 'weight',
                        span: 7,
                        rules: [
                          {required: true, message: '权重不能为空'},
                          {type: 'number', message: '权重必须为数字值'}
                        ],
                        externalValue: {
                          disabled: !this.judgeEditWeight('apply'),
                        }
                      },
                      {
                        type: "custom-input",
                        title: '工作内容',
                        model: 'jobContent',
                        span: 7,
                        externalValue: {
                          disabled: !this.judgeFormEditable('apply'),
                        }
                      },
                      {
                        type: 'delete',
                        externalValue: {
                          disabled: true,
                        },
                        callback: (index) => {
                          this.formPeopleWeightData.splice(index, 1);
                          this.formModel.membersList = this.formPeopleWeightData;
                          this.initFormSchema();
                        }
                      },
                    ],
                  }
                )
              }
              this.formModel.membersList = this.formPeopleWeightData;
            }
            if (project.feesList) {
              this.formFeesData = [];
              for (let i = 0; i < project.feesList.length; i++) {
                this.fileListData.push([]);
                this.fileListData[i] = project.feesList[i].executeCostFileData;
                this.formFeesData.push(
                  {
                    span: 24,
                    model: {
                      detailed: project.feesList[i].detailed,
                      amount: project.feesList[i].amount,
                      description: project.feesList[i].description,
                      executeCostFileData: project.feesList[i].executeCostFileData
                    },
                    schema: [
                      {
                        type: "custom-input",
                        title: '明细',
                        model: 'detailed',
                        span: 5,
                        externalValue: {
                          disabled: !this.judgeFormEditable('execute'),
                        }
                      },
                      {
                        type: "custom-input-number",
                        title: '金额',
                        model: 'amount',
                        span: 5,
                        rules: [
                          {required: true, message: '费用金额不能为空'},
                          {type: 'number', message: '费用金额必须为数字值'}
                        ],
                        externalValue: {
                          disabled: !this.judgeFormEditable('execute'),
                        }
                      },
                      {
                        type: "custom-input",
                        title: '备注',
                        model: 'description',
                        span: 5,
                        externalValue: {
                          disabled: !this.judgeFormEditable('execute'),
                        }
                      },
                      {
                        type: "custom-upload-file",
                        title: '费用单据',
                        model: 'executeCostFileData',
                        span: 5,
                        externalValue: {
                          disabled: !this.judgeFormEditable('execute'),
                          name: 'file',
                          actionUrl: `${baseUrl}/api/common/file-upload`,
                          requestHeader: {},
                          requestData: {},
                          uploadFileSuccess: (response, file, fileList) => {
                            if (response.status === 0) {
                              this.fileListData[i].push({
                                id: file.uid,
                                name: file.name + "-" + getItem("userName") + "-" + getItem("orgNameStr"),
                                url: baseUrl + response.data.url
                              });
                              this.initFormSchema();
                            } else {
                              this.$message.error(response.msg);
                            }
                          },
                          uploadFilePreview: (file) => {
                            window.open(file.url, '_blank');
                          },
                          uploadFileRemove: (file, fileList) => {
                            for (let j = 0; j < this.fileListData[i].length; j++) {
                              if (file.uid === this.fileListData[i][j].uid) {
                                this.fileListData[i].splice(j, 1);
                                break;
                              }
                            }
                            this.initFormSchema();
                          },
                          fileList: this.fileListData[i]
                        }
                      },
                      {
                        type: 'delete',
                        callback: (index) => {
                          this.fileListData.splice(index, 1);
                          this.formFeesData.splice(index, 1);
                          this.initFormSchema();
                        }
                      },
                    ],
                  },
                );
              }
            }
            this.formModel = project;
            if (result.data.activitiStatus == 0 || result.data.activitiStatus == 1 || result.data.activitiStatus == 3) {
              this.formModel.step = 2;
            }
            if (result.data.activitiStatus == 2 || result.data.activitiStatus == 4) {
              this.formModel.step = 3;
            }
            this.formModel.projectParentId = result.data.projectParentId;
            this.logOperationData = JSON.parse(JSON.stringify(this.formModel));
            if (result.data.ext.hasOwnProperty('applyFileData')) {
              this.formApplyFileData = result.data.ext.applyFileData;
            }
            if (result.data.ext.hasOwnProperty('executeFileData')) {
              this.formExecuteFileData = result.data.ext.executeFileData;
            }
            if (result.data.ext.hasOwnProperty('checkFileData')) {
              this.formCheckFileData = result.data.ext.checkFileData;
            }
            if (result.data.ext.hasOwnProperty('annotation')) {
              this.formModel.annotation = result.data.ext.annotation;
            }
            this.initFormBtn();
            this.initFormSchema();
          } else {
            this.$message.error(result.msg);
          }
        });
      },
      //获取可选项目
      getAvailableProject() {
        let projectCategory = '';
        let projectStep = '';
        switch (this.projectType) {
          case 'portrait':
            projectCategory = 'longitudinal';
            break;
          case 'market':
            projectCategory = 'market';
            break;
          case 'internal':
            projectCategory = 'internal';
            break;
        }
        switch (this.projectStep) {
          case 'apply':
            projectStep = 'declare';
            break;
          case 'verify':
            projectStep = 'review';
            break;
          case 'execute':
            projectStep = 'execute';
            break;
          case 'check':
            projectStep = 'accepting';
            break;
        }
        let param = {
          query: {
            category: projectCategory,
            step: projectStep,
          },
        };
        Api.ProjectManagement.getAvailableProject(param).then((result) => {
          this.loadingJudgeData.projectDataDone = true;
          if (result.status === 0) {

          } else {
            this.$message.error(result.msg);
          }
        });
      },
      //请求所有人员
      getAllPeople() {
        let params = {
          path: {
            id: 0
          }
        };
        Api.Administration.getPeers(params).then((result) => {
          this.loadingJudgeData.peopleDataDone = true;
          if (result.status === 0) {
            this.formProjectManagerData = this.assembleOrgData(result.data);
            this.formPeopleData = this.assembleOrgData(result.data);
          } else {
            this.$message.error(result.msg);
          }
        });
        // Api.PersonnelManagement.personListNew(1, 10000).then((result) => {
        //   this.loadingJudgeData.peopleDataDone = true;
        //   if (result.status === 0) {
        //     for (let i = 0; i < result.data.ls.length; i++) {
        //       let people = result.data.ls[i];
        //       this.formPeopleData.push({
        //         model: people.id,
        //         label: people.personName
        //       });
        //     }
        //   } else {
        //     this.$message.error(result.msg);
        //   }
        // });
      },
      //请求组织架构
      getOrganization() {
        Api.Common.getOrganization().then((result) => {
          this.loadingJudgeData.orgDataDone = true;
          if (result.status === 0) {
            this.formOrgData = this.assembleOrgData(result.data);
          } else {
            this.$message.error(result.msg);
          }
        });
      },
      //递归组装部门级联选择器数据源
      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;
      },
      selectorValueChanged(model) {
        if (model === 'projectId') {
          this.getProjectDetail(this.formModel.projectId);
        }
      },
      //人员去重和总权重等于100
      dynamicValueChanged(model, dynamicModel) {
        if (model === 'membersList' && dynamicModel === 'id') {
          // for (let i = 0; i < this.formPeopleData.length; i++) {
          //   this.formPeopleData[i] = {
          //     model: this.formPeopleData[i].model,
          //     label: this.formPeopleData[i].label,
          //     disabled: false
          //   };
          //   for (let j = 0; j < this.formPeopleWeightData.length; j++) {
          //     if (this.formPeopleData[i].model === this.formPeopleWeightData[j].model.id) {
          //       this.formPeopleData[i] = {
          //         model: this.formPeopleData[i].model,
          //         label: this.formPeopleData[i].label,
          //         disabled: true
          //       };
          //       break;
          //     }
          //   }
          // }
          this.initFormSchema();
        } else if (model === 'membersList' && dynamicModel === 'weight') {
          this.judgeProjectMemberInfo(false);
        }
      },
      //判断项目成员信息
      judgeProjectMemberInfo(equalToTen) {
        if (this.formPeopleWeightData.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择项目成员!'
          });
          return false;
        }
        let totalWeight = 0;
        for (let i = 0; i < this.formPeopleWeightData.length; i++) {
          totalWeight += this.formPeopleWeightData[i].model.weight;
        }
        if (equalToTen) {
          if (totalWeight !== 100) {
            this.$message({
              type: 'warning',
              message: '权重之和必须为100!'
            });
            return false;
          }
        }
        return true;
      },
      radioValueChanged(model) {
        this.initFormSchema();
      },
      //表单验证
      formValidate() {
        return this.$refs.childrenForm.validate();
      },
      //清空表单
      formResetFields() {
        //人员权重清空
        this.formPeopleWeightData = [];
        //人员权重去重清除
        // for (let i = 0; i < this.formPeopleData.length; i++) {
        //   this.formPeopleData[i] = {
        //     model: this.formPeopleData[i].model,
        //     label: this.formPeopleData[i].label,
        //     disabled: false
        //   };
        // }
        //执行费用清空
        this.formFeesTypeData = [];
        //上传文件清空
        this.formApplyFileData = [];
        this.formVerifyFileData = [];
        this.formExecuteFileData = [];
        this.formCheckFileData = [];
        this.$refs.childrenForm.resetFields();
        //重新加载form
        this.initFormSchema();
      },
      //取消提交
      formCancel() {
        this.formResetFields();
      },
      //项目执行阶段持续增加费用信息
      editProjectApply() {
        let projectStep = '';
        if (this.projectStep == 'check') {
          projectStep = 'accepting';
        } else if (this.projectStep == 'apply') {
          projectStep = 'declare';
        } else {
          projectStep = 'execute';
        }
        let projectCategory = '';
        switch (this.projectType) {
          case 'portrait':
            projectCategory = 'longitudinal';
            break;
          case 'market':
            projectCategory = 'market';
            break;
          case 'internal':
            projectCategory = 'internal';
            break;
        }
        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;
        debugger;
        let feesList = [];
        for (let i = 0; i < this.formFeesData.length; i++) {
          if (!this.formFeesData[i].model.amount) {
            this.$message.warning("费用金额不能为空！");
            return false;
          }
          this.formFeesData[i].model.executeCostFileData = this.fileListData[i];
          feesList.push(this.formFeesData[i].model);
        }
        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;
        //操作日志保存上传文件
        this.formModel.feesList = feesList;
        this.formModel.applyFileData = this.formApplyFileData;
        this.formModel.executeFileData = this.formExecuteFileData;
        this.formModel.checkFileData = this.formCheckFileData;

        let param = {
          path: {
            id: this.formModel.projectId
          },
          data: {
            projectCategory: projectCategory,
            projectStep: projectStep,
            projectName: this.formModel.projectName,
            projectNo: this.formModel.projectNo,
            projectParentId: this.formModel.projectParentId,
            description: this.formModel.description,
            ext: ext
          }
        };
        this.loadingJudgeData.coreDataDone = false;
        Api.ProjectManagement.editProject(param).then((result) => {
          this.loadingJudgeData.coreDataDone = true;
          if (result.status === 0) {
            let message = '';
            if (this.canEdit) {
              message = '编辑成功!';
            } else {
              message = '保存成功!';
            }
            this.$message({
              type: 'success',
              message: message
            });
            this.$refs.logChildren.addCperationLog();
            this.formResetFields();
            this.$router.go(-1);
          } else {
            this.$message.error(result.msg);
          }
        });
      },
      //项目执行阶段提交审批
      submitProjectApplyToVerify() {
        if (this.checkFileData == false) {
          this.$message.warning("请上传执行附件！");
          return false;
        }
        let projectStep = '';
        if (this.projectStep == 'check') {
          projectStep = 'accepting';
        } else {
          projectStep = 'execute';
        }
        let projectCategory = '';
        switch (this.projectType) {
          case 'portrait':
            projectCategory = 'longitudinal';
            break;
          case 'market':
            projectCategory = 'market';
            break;
          case 'internal':
            projectCategory = 'internal';
            break;
        }
        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 = [];
        for (let i = 0; i < this.formFeesData.length; i++) {
          if (!this.formFeesData[i].model.amount) {
            this.$message.warning("费用金额不能为空！");
            return false;
          }
          this.formFeesData[i].model.executeCostFileData = this.fileListData[i];
          feesList.push(this.formFeesData[i].model);
        }
        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;
        //操作日志保存上传文件
        this.formModel.feesList = feesList;
        this.formModel.applyFileData = this.formApplyFileData;
        this.formModel.executeFileData = this.formExecuteFileData;
        this.formModel.checkFileData = this.formCheckFileData;
        let param = {
          path: {
            id: this.formModel.projectId
          },
          data: {
            projectCategory: projectCategory,
            projectStep: projectStep,
            projectName: this.formModel.projectName,
            projectNo: this.formModel.projectNo,
            projectParentId: this.formModel.projectParentId,
            description: this.formModel.description,
            ext: ext
          }
        };
        this.loadingJudgeData.coreDataDone = false;
        Api.ProjectManagement.submitProjectToVerify(param).then((result) => {
          this.loadingJudgeData.coreDataDone = true;
          if (result.status === 0) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.$refs.logChildren.addCperationLog();
            this.$router.go(-1);
          } else {
            this.$message.error(result.msg);
          }
        });
      },
    },
    components: {
      PageLoading, DataForm, FlowRecordTable, VerifyButton, LogDataTable
    }
  }
</script>

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

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