<!--
  @description: 京能采购计划编辑-录入采购计划（新增）
  @author: lxl
  @routerPath:/procurementPlan/procurementPlanEntryAdd
  /procurement/purPlanningAdd
  @date： 2020-8-3 13:56:01
-->
<template>
  <div class="p0-16">
    <!--标题-->
    <section class="title">
      <i v-if="backType!=='01'" class="iconfont icon-fanhui pointer" @click="back()" />
      录入采购计划
    </section>
    <p class="page-title">
      1.采购计划基本信息
    </p>
    <el-form ref="form" :model="formData" :rules="rules" :inline-message="true">
      <table class="from_table">
        <tr>
          <td><el-form-item label="采购计划编号" prop="purchasePlanNo" /></td>
          <td>
            <gx-input
              v-model="formData.purchasePlanNo"
              gx-maxlength="varchar50"
              :disabled="tenderNoStatus"
              placeholder="采购计划编号"
              clearable
            />
          </td>
          <td><el-form-item label="采购计划名称" prop="purchasePlanName" /></td>
          <td>
            <gx-input
              v-model="formData.purchasePlanName"
              placeholder="最多允许输入100字符"
              gx-maxlength="varchar100"
              show-word-limit
              clearable
            />
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="采购组织形式" prop="purchaseOrganization" />
          </td>
          <td :colspan="formData.purchaseOrganization==='01'?'0':'3'">
            <el-radio-group
              v-model="formData.purchaseOrganization"
              :disabled="disabledType"
            >
              <el-radio
                v-for="item in plan_purchase_organizationList"
                :key="item.typecode"
                :label="item.typecode"
              >
                {{ item.typename }}
              </el-radio>
            </el-radio-group>
          </td>
          <td v-if="formData.purchaseOrganization==='01'">
            <el-form-item label="执行机构" prop="agentDepartName" />
          </td>
          <td v-if="formData.purchaseOrganization==='01'">
            <gx-input
              v-model="formData.agentDepartName"
              gx-maxlength="varchar500"
              disabled
              style="width: calc(100% - 168px );"
            />
            <!-- 请选择 -->
            <el-button
              type="primary"
              @click="onSelProxy"
            >
              选择
            </el-button>
            <el-button plain @click="consignContractInfo('clear')">
              清空
            </el-button>
          </td>
        </tr>
        <!--委托采购-是否 （00集中委托 01-代理委托）-->
        <tr v-if="formData.purchaseOrganization==='01' && whetherPurchaser==='01'">
          <td>
            <el-form-item label="项目经理" prop="agentRealName" />
          </td>
          <td>
            <gx-input
              v-model="formData.agentRealName"
              gx-maxlength="varchar500"
              disabled
              style="width: calc(100% - 168px );"
            />
            <!-- 请选择 -->
            <el-button
              type="primary"
              :disabled="managerDisable"
              @click="dialogManagerData.consignContractVisible = true"
            >
              选择
            </el-button>
            <el-button plain @click="consignMangContractInfo('clear')">
              清空
            </el-button>
          </td>
          <td>
            <el-form-item label="联系方式" prop="contactNumber" />
          </td>
          <td>
            <gx-input
              v-model="formData.contactNumber"
              gx-maxlength="varchar50"
              show-word-limit
              disabled
            />
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="采购计划类型" prop="purchaseType" />
          </td>
          <td colspan="3">
            <el-form-item>
              <el-radio-group
                v-model="formData.purchaseType"
                :disabled="disabledType"
              >
                <el-radio
                  v-for="item in plan_typeList"
                  :key="item.typecode"
                  :label="item.typecode"
                >
                  {{ item.typename }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </td>
        </tr>
      </table>
    </el-form>
    <el-row :gutter="40">
      <el-col :md="24" :lg="24" class="mt10 mb10">
        <span class="page-title">2.行项目信息</span>
        <el-button
          style="margin-left: 10px"
          class="m10 mr10"
          type="primary"
          icon="el-icon-plus"
          @click="addRow"
        >
          添加行项目信息
        </el-button>
        <el-upload
          ref="uploads"
          :on-success="handleSuccess"
          :on-error="handleError"
          :headers="importHeaders"
          :show-file-list="false"
          :action="action"
          :data="upLoadData"
          multiple
          class="mr10"
          style="display: inline-block;"
        >
          <el-button>模板导入</el-button>
        </el-upload>
        <el-button :loading="downLoading" @click="downloadClick">
          下载模板文件
        </el-button>
      </el-col>
    </el-row>
    <!--行项目信息编辑列表-->
    <div>
      <addLineItemTable :loading="loading" :line-project-data="lineProjectData" :detail-ider="detailIder" @watchData="watchData" @planDetail="planDetail" @checkFile="onCheckFile" />
      <!--分页组件-->
      <pagination :pagination-data="paginationData" @change="initLineInfoData" />
    </div>
    <!--保存按钮-->
    <div class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <!-- 提交 -->
          <el-button
            :loading="confirmStepLoading"
            type="primary"
            @click="nextStep('form')"
          >
            提 交
          </el-button>
          <!-- 保存 -->
          <el-button
            :loading="confirmStepLoading"
            @click="save('form')"
          >
            保 存
          </el-button>
        </div>
      </div>
    </div>
    <!--添加行项目信息弹框-->
    <addLineItemInfoDialog
      v-if="dialogData.consignContractVisible"
      :dialog-data="dialogData"
      :planmainid="upLoadData.planMainId"
      @saveconsignContractInfo="saveconsignContractInfo"
    />
    <!--代理机构-->
    <entryAgent-dialog :dialog-data="dialogAgencyData" :depart-id="departId" @consignContractInfo="consignContractInfo" />
    <!--项目经理弹框-->
    <entryProjectManger-dialog :dialog-data="dialogManagerData" @consignMangContractInfo="consignMangContractInfo" />
    <!-- 查看附件 -->
    <checkFIleCompDialog :dialog-file-data="dialogFileData" />
    <!-- 工作流 -->
    <template v-if="purchasplanEntryAuditConfig">
      <!--工作流选择节点组件-->
      <processNode-com
        ref="processNode"
        :process-definition-key="processDefinitionKey"
        @processNodeData="processNodeData"
      />
      <!--工作流流程节点/获取审核用户-->
      <depart-dialog
        ref="departDialog"
        :process-node="processNode"
        @isSingleUser="isSingleUser"
        @processInitData="processInitData"
        @submit="submit"
      />
    </template>
  </div>
</template>
<script>
/* 接口*/
import {
  queryPurchasePlanMainInfo, // 项目信息
  listPurchasePlanMainDetailPages, // 行项目信息
  savePurchasePlanMainInfo, // 提交/保存
  importPlanDetailInfoList // 导入
} from '@/api/procurement/purchasplan'
import { getSystemConfigValueByConfigType } from '@/api/common/systemConfigCenter'
import { downloadTemplate } from '@/api/procurement/datacenterDangtfz' // 导入接口
/* 公共方法*/
import { ListMixin } from '@/mixins/ListMixin' // 分页
import { procurementPlanGrounpMixins } from '../../mixins/procurementPlanGroupMixins'
/* 公共组件*/
import pagination from '@comp/common/pagination/pagination' // 分页组件
import { characters1_auto, checkLinktel, checkNum } from '@/assets/js/validate'// 校验输入内容
/* ==========工作流===========*/
import { workCommonMixins } from '@/views/work/mixins/workCommonMixins' // 工作流公共配置
import workconstant from '@/assets/js/workutils/workconstant/procurement' // 配置流程key
import processNodeCom from '@/views/work/processNodeCom' // 工作流选择节点组件
import departDialog from '@/views/work/depart-dialog' // 选择审核人员
/* ============================*/
/*  弹框 */
import addLineItemInfoDialog from './addLineItemInfo-dialog' // 录入物资弹框
import entryAgent from './organization-dialog' // 录入代理机构弹框
import entryProjectManger from './manager-dialog' // 录入项目经理弹框
import checkFIleCompDialog from '@/views/procurement/procurementPlan/components/checkFIleComp-dialog.vue'// 查看附件

import addLineItemTable from './addLineItemTable' // 行项目物资组件
import Cookies from 'js-cookie'
import { download } from '@/assets/js/utils/index' // 文件回显组件
export default {
  name: 'PurPlanningAdd',
  components: {
    'entryProjectManger-dialog': entryProjectManger, // 录入项目经理弹框
    'entryAgent-dialog': entryAgent, // 录入代理机构弹框
    addLineItemInfoDialog, // 录入物资弹框
    addLineItemTable, // 行项目物资组件
    pagination, // 分页组件
    checkFIleCompDialog, // 查看附件
    'processNode-com': processNodeCom, // 工作流节点信息组件
    'depart-dialog': departDialog // 工作流审批人组件
  },
  mixins: [ListMixin, workCommonMixins, procurementPlanGrounpMixins],
  data() {
    return {
      loading: true, // 行项目表格loading
      action: importPlanDetailInfoList, // 导入接口
      backType: this.$route.meta.backType, // 路由退回状态
      // createURL: createURL,
      importHeaders: {}, // 导入用户信息
      upLoadData: { // 模板导入数据
        planMainId: ''
      },
      processDefinitionKey: '', // 工作流流程key
      operation: '', // 00保存/01提交
      disabledType: false, // 自行采购disbale状态
      detailIder: this.$route.params.detailIder, // 00查看标识 01编辑
      confirmStepLoading: false, // 提交button confirmLoading状态
      downLoading: false, // 下载模板loading
      tenderNoStatus: true, // 采购计划编号禁用状态 默认禁用 二次进入时可编辑
      // 项目经理-展示/隐藏状态 true 展示/false 隐藏
      dialogManagerData: {
        consignContractVisible: false,
        departId: '',
        purchasePlanNo: '', // 计划编号
        purchasePlanName: '' // 计划名称
      },
      // 添加行项目信息-展示/隐藏状态 true 展示/false 隐藏
      dialogData: { // 添加行项目信息弹框数据
        consignContractVisible: false,
        planDetailId: '',
        planAdd: '',
        purchasePlanNo: '', // 计划编号
        purchasePlanName: '' // 计划名称
      },
      dialogFileData: {
        checkFileVisible: false, // 查看附件弹框状态
        bizId: '' // 附件id
      },
      departId: '',
      // 代理机构-展示/隐藏状态 true 展示/false 隐藏
      dialogAgencyData: {
        consignContractVisible: false
      },
      lineProjectData: [], // 行项目信息
      formData: {
        purchaseOrganization: '00', // 采购形式组织
        purchaseType: '00' // 采购计划类型
      },
      // 校验规则
      rules: {
        // 采购计划编码
        purchasePlanNo: [{ required: true, validator: characters1_auto, trigger: 'blur' }],
        // 采购计划名称
        purchasePlanName: [{ required: true, validator: characters1_auto, trigger: 'blur' }],
        purchaseType: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 采购计划类型
        purchaseOrganization: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 代理机构
        agentDepartName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 项目经理
        agentRealName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 联系方式
        contactNumber: [{ required: true, validator: checkLinktel, trigger: 'blur' }], // 手机号
        purchaseNum: [{ required: true, validator: checkNum, trigger: 'blur' }], // 数量
        purchaseSpecification: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 规格
        purchaseName: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 物资名称
        deliveryAddress: [{ required: true, validator: characters1_auto, trigger: 'blur' }], // 交货地点
        purchaseUnit: [{ required: true, message: '请选择', trigger: 'change' }], // 计量单位
        purchaseTaxRate: [{ required: true, message: '请选择', trigger: 'change' }], // 税率
        // materialType: [{ required: true, message: '请选择', trigger: 'change' }], // 物资类型
        deliveryTime: [{ required: true, message: '请选择', trigger: 'blur' }], // 交货时间
        smallName: [{ required: true, message: '请选择', trigger: 'change' }] // 物资小类名称
      },
      purchasplanEntryAuditConfig: false, // true启动工作流 false普通审核
      whetherPurchaser: '' // 委托采购-是否 （00集中委托 01-代理委托）
    }
  },
  computed: {
    // 选择项目经理按钮状态
    managerDisable() {
      if (this.formData.agentDepartName) {
        return false
      }
      return true
    }
  },
  created() {
    this.importHeaders['X-AUTH-TOKEN'] = Cookies.get('X-AUTH-TOKEN') // 获取用户token
    this.initData() // 采购计划基本信息
    this.getNodeId() // 获取工作流key
    this.getSystemConfig()
    // 根据键获取正式配置
    this.$store.dispatch('getSystemConfigValue', 'purchasplan-entry-audit-config').then(() => {
      this.purchasplanEntryAuditConfig = this.$store.getters.systemConfigVo.configType // true启动工作流 false普通审核
    }).catch(() => {
    })
  },
  methods: {
    // 根据键获取配置 委托采购-是否 （00-否 01-是） （00集中委托 01-代理委托）
    getSystemConfig() {
      getSystemConfigValueByConfigType('whether_assign_purchaser').then((res) => {
        this.whetherPurchaser = res.data
      })
    },
    // 下载计划详情模板
    downloadClick() {
      //  模板类型
      const data = {
        templateType: 'P_T_P_PURCHASPLAN_PLANDETAILTEMPLATE'
      }
      this.downLoading = true
      downloadTemplate(data).then(res => {
        this.downLoading = false
        download(res, '计划详情模板.xls')
      }).catch(() => {
        this.downLoading = false
      })
    },
    // 模板导入成功后的回调
    handleSuccess(response, file, fileList) {
      // 模板导入成功后
      if (response.header.ret === '0') {
        this.$message.success(response.header.msg)
      } else {
        // 上传失败
        this.$message.warning(response.header.msg)
      }
      //  清空
      this.$refs.uploads.clearFiles()
      // 加载行项目数据列表方法
      this.initLineInfoData()
    },
    // 模板导入失败后的回调
    handleError(response, file, fileList) {
      this.$message.error(response.header.msg)
      this.$refs.uploads.clearFiles()
      this.initLineInfoData()
    },
    /*
     * 选择新增物资回调函数
     * val参数 val 值true点击弹框确定按钮
     * */
    saveconsignContractInfo(val) {
      if (val) {
        this.initLineInfoData()
      }
    },
    // 项目经理
    consignMangContractInfo(data) {
      if (data === 'clear') { // 清空
        this.formData.agentRealName = '' // 采购代理人员姓名
        this.formData.agentRoleCode = ''// 采购代理人员角色code
        this.formData.agentId = ''// 采购代理人员ID
      } else { // 选择
        this.formData.contactNumber = data.mobilePhone// 手机号
        this.formData.agentRealName = data.realName// 采购代理人员姓名
        this.formData.agentRoleCode = data.roleCode// 采购代理人员角色code
        this.formData.agentId = data.userId// 采购代理人员ID
      }
    },
    // 选择代理机构
    onSelProxy() {
      this.dialogAgencyData.consignContractVisible = true
    },
    // 代理机构
    consignContractInfo(data) {
      if (data === 'clear') { // 清空
        this.formData.agentDepartName = ''// 代理机构名称
        this.formData.agentDepartId = ''// 机构id
        this.consignMangContractInfo('clear') // 清空项目经理
      } else { // 选择
        if (this.formData.agentDepartName !== data.departname) {
          this.formData.agentRealName = '' // 清空项目的值
        }
        this.formData.agentDepartName = data.departname// 代理机构名称
        this.formData.agentDepartId = data.id// 机构id
        this.dialogManagerData.departId = data.id// 项目经理-机构id
        this.departId = data.id// 项目经理-机构id
      }
    },
    // 查看附件
    onCheckFile(res, flg) {
      this.dialogFileData.checkFileVisible = flg
      this.dialogFileData.bizId = res.planDetailId
    },
    // 开启行项目信息开启弹框
    addRow() {
      // 开启弹框
      this.dialogData.planAdd = '00'
      this.dialogData.purchasePlanNo = this.formData.purchasePlanNo // 计划编号
      this.dialogData.purchasePlanName = this.formData.purchasePlanName // 计划名称
      this.dialogData.collectionType = this.formData.purchaseOrganization // 采购组织形式
      this.dialogData.consignContractVisible = true
    },
    /*
    * 行项目信息编辑触发
    * */
    planDetail(data) {
      this.dialogData.planDetailId = data.planDetailId // 计划详情id
      this.dialogData.planAdd = data.planAdd
      this.dialogData.purchasePlanNo = this.formData.purchasePlanNo // 计划编号
      this.dialogData.purchasePlanName = this.formData.purchasePlanName // 计划名称
      this.dialogData.consignContractVisible = true // 弹框状态
    },
    /*
     * 行项目信息删除触发回调函数
     * val参数 val 值true表示已删除
     * */
    watchData(val) {
      if (val) {
        // 调用获取行项目信息方法
        this.initLineInfoData()
      }
    },
    // 保存提交数据
    assetsData() {
      // 采购计划基本信息
      const projectInfo = {
        purchasePlanNo: this.formData.purchasePlanNo, // 采购计划编码
        purchasePlanName: this.formData.purchasePlanName, // 采购计划名称
        purchaseOrganization: this.formData.purchaseOrganization, // 采购组织形式
        agentPurchaseDepartName: this.formData.agentDepartName, // 代理机构
        agentPurchaseDepartId: this.formData.agentDepartId, // 代理id
        agentRealName: this.formData.agentRealName, // 采购代理人员姓名
        agentRoleCode: this.formData.agentRoleCode, // 采购代理人员角色code
        agentId: this.formData.agentId, // 采购代理人员ID
        contactNumber: this.formData.contactNumber, // 手机号
        id: this.upLoadData.planMainId, // 计划id
        purchaseType: this.formData.purchaseType, // 采购类型
        planType: '00', // 计划类型
        operation: '', // 保存
        whetherAssignPurchaser: this.whetherPurchaser
      }
      return projectInfo
    },
    getNodeId() {
      this.processDefinitionKey = workconstant.purPlanMainAudit // 工作流流程key
    },
    // 保存
    save() {
      this.confirmLoading = true
      // 获取保存参数
      const data = this.assetsData()
      data.operation = '00'// 保存
      // 调用保存数据方法
      this.saveData(data)
    },
    // 提交
    nextStep(formName) {
      if (this.lineProjectData.length <= 0) {
        this.$message.warning('请添加行项目信息')
        return false
      }
      this.$refs[formName].validate((valid, field) => {
        if (valid) {
          // 获取保存参数
          this.$confirm('提交之后将不能更改，确认提交吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            confirmButtonClass: 'confirmBtn',
            cancelButtonClass: 'cancelBtn'
          }).then(() => {
            /* purchasplanEntryAuditConfig true启动工作流 false普通审核*/
            if (this.purchasplanEntryAuditConfig) {
              // 启动工作流
              if (JSON.stringify(this.processNode) !== '{}' && this.processNode.nodeId) {
                this.$refs.departDialog.getUserDepart(this.processNode)
              }
            } else {
              // 直接提交
              this.submit()
            }
          }).catch(() => {
          })
        } else {
          return false
        }
      })
    },
    // 审批流提交
    submit() {
      const data = this.assetsData()
      data.operation = this.operation
      data.operation = '01'// 提交
      if (this.purchasplanEntryAuditConfig) {
        this.processInitDto.type = '01' // 01：初次提交 02：审核驳回再次提交
        data.processInitDto = this.processInitDto // 审核人信息传回得信息
      }
      this.saveData(data)
    },
    // 封装保存数据请求方法
    saveData(data) {
      this.confirmStepLoading = true
      savePurchasePlanMainInfo(data).then(res => {
        this.confirmStepLoading = false
        this.back()
      }).catch(() => {
        this.confirmStepLoading = false
      })
    },
    // 封装获取项目基本信息请求方法
    initData() {
      const params = {
        planMainId: this.$route.params.planMainId || this.$route.query.id || '',
        planType: '00' // 计划类型
      }
      queryPurchasePlanMainInfo(params).then(res => {
        this.upLoadData.planMainId = res.data.id
        this.formData = {
          ...res.data
          // purchaseOrganization: '00'
        }
        // // 判断采购组织形式是否有值 没值给默认
        if (!this.formData.purchaseOrganization) {
          this.formData.purchaseOrganization = '00'
        }
        // 判断采购计划类型是否有值 没值给默认
        if (!this.formData.purchaseType) {
          this.formData.purchaseType = '00'
        }
        this.initLineInfoData()
      }).catch(() => {})
    },
    // 封装行项目信息请求方法
    initLineInfoData() {
      // 查询条件
      const params = {
        planMainId: this.upLoadData.planMainId, // 计划id
        pageNo: this.paginationData.pageNo,
        pageSize: this.paginationData.pageSize
      }
      listPurchasePlanMainDetailPages(params).then(res => {
        this.loading = false
        this.lineProjectData = res.data.records
        // 获取条数
        this.paginationData.total = res.data.total
      }).catch(() => {
        this.loading = false
      })
    },
    // 返回按钮
    back() {
      if (this.backType) {
        this.$router.push('/home')
      } else {
        this.$router.push('procurementPlanEntryList')
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
