<!--
  @description: 立项-标的清单-无采购计划
  @Modifier: haoFx
  @routerPath: /bidding/bidProjectStep/bidProjectMateriel
  @date: 2019/10/25-18:20
-->
<template>
  <div>
    <div class="mb16">
      <div class="mb16 clearfix">
        <div class="fl">
          <!--isProcurementPlan 无招标计划显示-->
          <el-button
            v-if="isProcurementPlan==='00'"
            type="primary"
            icon="iconfont icon-tianjia1"
            @click="addRow"
          >
            增加物料信息
          </el-button>
          <!--新产品展示下载物料模板和上传-->
          <template v-if="!bidProjectSystemSourceType">
            <el-upload
              ref="upload"
              :action="saveExcelToolsExcelUrl"
              :on-success="handleSuccess"
              :limit="1"
              :data="queryMaterieData"
              :show-file-list="false"
              :headers="importHeaders"
              multiple
              style="display: inline-block;margin-left: 10px"
            >
              <el-button>物料上传</el-button>
            </el-upload>
            <el-button style="margin: 0 10px" type="text" @click="getFileUrl">
              下载物料模板
            </el-button>
          </template>
        </div>
        <div class="fr">
          <span>预算总额总计：</span>
          <span class="red-star">{{ moneyFormat(summaries) }}</span>
          <span class="summaries">（元）</span>
          <el-button @click="exportMateriel">
            导出物料
          </el-button>
        </div>
      </div>
      <el-form ref="forms" :model="formData" :rules="formData.rules" inline-message>
        <div>
          <el-table
            :data="showTenderMaterielInfoList"
          >
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
            />
            <el-table-column
              min-width="270"
              header-align="center"
            >
              <template slot="header">
                <span>物料编码</span>
              </template>
              <template slot-scope="scope">
                <template>
                  <!--
                    :prop="'tenderMaterielInfoList.' + scope.$index + '.productNo'"
                    :rules="formData.rules.productNo"
                     -->
                  <el-form-item
                    v-if="scope.row.state"
                  >
                    <gx-input
                      v-model.trim="scope.row.productNo"
                      gx-maxlength="varchar1000"
                      style="width:calc(100% - 70px)"
                      size="mini"
                    />
                    <span class="fr">
                      <el-link :underline="false" type="primary" @click="selectMaterial(scope.row,scope.$index)">
                        选择
                      </el-link>
                      <el-link :underline="false" type="primary" @click="empty(scope.$index)">
                        清空
                      </el-link>
                    </span>
                  </el-form-item>
                  <span v-else v-text="scope.row.productNo" />
                </template>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              min-width="270"
            >
              <template slot="header">
                <span>产品名称</span>
              </template>
              <template slot-scope="scope">
                <template>
                  <!--
                    :prop="'tenderMaterielInfoList.' + scope.$index + '.productName'"
                    :rules="formData.rules.productName"
                   -->
                  <el-form-item
                    v-if="scope.row.state"
                  >
                    <gx-input
                      v-model.trim="scope.row.productName"
                      gx-maxlength="varchar1000"
                      size="mini"
                    />
                  </el-form-item>
                  <span v-else v-text="scope.row.productName" />
                </template>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              min-width="200"
              align="left"
            >
              <template slot="header">
                <span class="red-star">*</span>
                <span>物料型号或工程服务明细</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.state"
                  :prop="'tenderMaterielInfoList.' + scope.$index + '.productModel'"
                  :rules="formData.rules.productModel"
                >
                  <gx-input
                    v-model.trim="scope.row.productModel"
                    gx-maxlength="varchar200"
                    size="mini"
                  />
                </el-form-item>
                <span v-else v-text="scope.row.productModel" />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="right"
              min-width="100"
            >
              <template slot="header">
                <span class="red-star">*</span>
                <span>数量</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.state"
                  :prop="'tenderMaterielInfoList.' + scope.$index + '.quantity'"
                  :rules="formData.rules.quantity"
                >
                  <money
                    v-if="scope.row.state"
                    :unit-fixed="0"
                    :money-value="scope.row"
                    size="mini"
                    width="auto"
                    name="quantity"
                    @input="getSummaries()"
                  />
                </el-form-item>
                <span v-else>{{ scope.row.quantity }}</span>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="left"
              min-width="200"
            >
              <template slot="header">
                <span class="red-star">*</span>
                <span>单位</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.state"
                  :prop="'tenderMaterielInfoList.' + scope.$index + '.unit'"
                  :rules="formData.rules.unit"
                >
                  <gx-input
                    v-if="scope.row.state"
                    v-model.trim="scope.row.unit"
                    gx-maxlength="varchar50"
                    size="mini"
                  />
                </el-form-item>
                <span v-else v-text="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="right"
              min-width="160"
            >
              <template slot="header">
                <span class="red-star">*</span>
                <span>预算单价（元）</span>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.state"
                  :prop="'tenderMaterielInfoList.' + scope.$index + '.unitBudget'"
                  :rules="formData.rules.unitBudget"
                >
                  <money
                    v-if="scope.row.state"
                    :money-value="scope.row"
                    width="auto"
                    size="mini"
                    name="unitBudget"
                    @input="getSummaries()"
                  />
                </el-form-item>
                <span v-else>{{ scope.row.unitBudget }}</span>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="right"
              min-width="160"
            >
              <template slot="header">
                <span class="red-star">*</span>
                <span>预算总额（元）</span>
              </template>
              <template slot-scope="scope">
                <span>{{ moneyFormat(scope.row.totalBudget) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              label="操作"
              fixed="right"
              align="center"
              width="130"
            >
              <template slot-scope="scope">
                <el-link
                  v-if="!scope.row.state"
                  type="primary"
                  @click="editRow(scope.row,scope.$index,true)"
                >
                  [编辑]
                </el-link>
                <el-link
                  v-else
                  type="primary"
                  @click="editRow(scope.row,scope.$index,false)"
                >
                  [保存]
                </el-link>
                <el-link
                  type="primary"
                  @click="deleteRow(scope.$index,scope.row)"
                >
                  [删除]
                </el-link>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination :pagination-data="paginationData" @change="paginData" />
        </div>
      </el-form>
    </div>
    <!--保存按钮-->
    <div class="but_footer">
      <div class="but_footer-h">
        <div class="but_footer-but">
          <el-button @click="prevStep">
            上一步
          </el-button>
          <el-button :loading="confirmLoading" type="primary" @click="nextStep">
            暂存，进入下一步
          </el-button>
        </div>
      </div>
    </div>
    <!-- 品目树弹框-->
    <category-tree-dialog :dialog-data="dialogData" @categoryTreeInfo="categoryTreeInfo" />
  </div>
</template>

<script>
/* 接口*/
import { saveTenderMaterielInfo, listTenderMaterie, saveSingleTenderMaterielInfo, removeTenderMaterielInfo,
  saveMaterielByExcel,
  exportMaterielList } from '@/api/bidding/biddingProject'// 物料保存 物料查询列表
import { downLoadFile } from '@/api/common/uploadCenter'
import { getSystemConfigValueByConfigType } from '@/api/common/systemConfigCenter'// 产品分类品目树
/* 公用方法*/
import { cloneObject, moneyFormat, download, paging } from '@assets/js/utils'// 常用方法
import { validateRoleCode, validateInput, characters1_auto } from '@/assets/js/validate'// 校验输入内容
import Cookies from 'js-cookie'
/* 混入公共方法*/
import { ListMixin } from '@/mixins/ListMixin'// 分页/* 混入-字典信息 */
import { bidProjectCommon } from '../mixins/bidProjectCommon'
/* 组件*/
import money from '@comp/common/money/money'// 金额
import categoryTreeDialog from '@/views/common/tools/categoryTree-dialog'
import pagination from '@comp/common/pagination/pagination'// 分页

export default {
  name: 'BidProjectMaterielAdd',
  components: {
    money, // 金额
    'category-tree-dialog': categoryTreeDialog, // 品目树组件
    pagination// 分页
  },
  mixins: [ListMixin, bidProjectCommon],
  data() {
    return {
      moneyFormat: moneyFormat, // 金额添加千分位
      saveExcelToolsExcelUrl: saveMaterielByExcel, // 上传表格
      summaries: 0, // 预算总额总计
      confirmLoading: false, // 暂存、下一步Loding
      // 弹窗-展示/隐藏状态 true 展示/false 隐藏
      dialogData: {
        title: '选择物料', // 弹框标题
        dialog: false, // 供货范围
        onlyOneSelected: true, // 是否只能选最后一级且是单选
        selectCodes: [] // 当前选中的供货范围Code
      },
      // 创建/增加的物料信息字段
      addData: {
        id: '', // 项目物料id （修改时赋值）
        isBelong: '00', // 是否归属包组 00:否 01:是
        planDetailId: '', // 计划明细id
        planMainId: '', // 计划主表id
        unit: '', // 计量单位
        priceUnit: '01', // 预算单价单位 00:万元 01:元
        productModel: '', // 物料货号/型号
        productName: '', // 物料名称
        productNo: '', // 物料编号
        quantity: '', // 数量
        sortNo: 0, // 排序
        split: '00', // 是否拆分 00未拆分 01已拆分
        tenderId: '', // 项目ID
        unitBudget: '', // 单价
        totalBudget: 0, // 预算总额
        useStatus: '00', // 有效状态 00:临时(草稿) 01:有效 02:作废
        state: true // 设置表格为可编辑状态
      },
      importHeaders: {}, // cookie信息
      fileUrl: '',
      formData: {
        rules: {
          productNo: [
            { required: true, validator: characters1_auto, trigger: 'blur' },
            { validator: validateInput, trigger: 'blur' },
            { validator: validateRoleCode, trigger: 'blur' }
          ],
          productName: [{ required: true, validator: characters1_auto, trigger: 'blur' }],
          productModel: [{ required: true, validator: characters1_auto, trigger: 'blur' }],
          quantity: [{ required: true, validator: characters1_auto, trigger: 'blur' }],
          unit: [{ required: true, validator: characters1_auto, trigger: 'blur' }],
          unitBudget: [{ required: true, validator: characters1_auto, trigger: 'blur' }]
        },
        tenderMaterielInfoList: [] // 物料列表
      },
      isProcurementPlan: '', // 是否有招标计划 00 否 01是
      showTenderMaterielInfoList: [], // 展示的物料列表
      // 物料上传参数
      queryMaterieData: {
        tenderId: ''
      },
      mattersTemplateFileId: '' // 物料文件id
    }
  },
  created() {
    this.getSystemSource()
    this.addData.tenderId = this.projectData.id
    this.queryMaterieData.tenderId = this.projectData.id
    this.importHeaders['X-AUTH-TOKEN'] = Cookies.get('X-AUTH-TOKEN')
    this.isProcurementPlan = sessionStorage.getItem('isProcurementPlan')
  },
  mounted() {
    // 进入页面调用查询项目物料列表
    this.initData()
  },
  methods: {
    // 新产品的查询物料下载模板的配置
    getSystemSource() {
      getSystemConfigValueByConfigType('biddingProject_matters_template_file_id').then(res => {
        this.mattersTemplateFileId = res.data
      }).catch(() => {
      })
    },
    // 下载模板拼接地址
    getFileUrl() {
      const data = {
        fileId: this.mattersTemplateFileId,
        fileType: 'winService_winServiceFile_base'
      }
      downLoadFile(data).then((res) => {
        download(res, '物料模板.xlsx')
      }).catch(() => {
      })
    },
    /* =========================挑选品目Start===========================*/
    // 挑选品目
    selectMaterial(row, index) {
      // 已选中的品目
      this.dialogData.selectCodes = this.showTenderMaterielInfoList[index] && this.showTenderMaterielInfoList[index].productNo.split(',') || []
      // 当前操作的索引下标
      this.dialogData.index = index
      // 打开弹框
      this.dialogData.dialog = true
    },
    // 已选品目
    categoryTreeInfo(data) {
      this.showTenderMaterielInfoList[this.dialogData.index].productNo = data.keys // 物料编码
      this.showTenderMaterielInfoList[this.dialogData.index].productName = data.labels // 物料名称
    },
    // 清空已选品目
    empty(index) {
      this.showTenderMaterielInfoList[index].productNo = ''
      this.showTenderMaterielInfoList[index].productName = ''
    },
    /* =========================挑选品目End===========================*/
    // 预算金额总计
    getSummaries() {
      let contractBudget = 0
      this.formData.tenderMaterielInfoList.map(item => {
        if (item.quantity && item.unitBudget) {
          item.totalBudget = Number(item.unitBudget * item.quantity).toFixed(2)
        } else {
          item.totalBudget = 0
        }
        contractBudget += Number(item.totalBudget)
      })
      this.summaries = contractBudget.toFixed(2)
    },
    // 查询项目物料列表
    initData() {
      const params = {
        tenderId: this.queryMaterieData.tenderId
      }
      listTenderMaterie(params).then(response => {
        if (response.data) {
          this.formData.tenderMaterielInfoList = response.data // 回显物料列表
          // 判断是否有招标计划 有则执行此操作
          if (this.isProcurementPlan === '01') {
            this.formData.tenderMaterielInfoList.map((item) => {
              if (item.schemeId) {
                item.taskPlan = {
                  annualPrequalificationScreeningProject: item.annualPrequalificationScreeningProject, // 年度资格预审筛选项目 00:否 01:是
                  qualificationCheckWay: item.qualificationCheckWay, // 资格审查方式，00单次资格预审，01年度资格预审，02资格后审
                  schemeMatterId: item.schemeMatterId, // 招标计划关联id
                  schemeId: item.schemeId, // 采购计划ID
                  schemeName: item.schemeName, // 计划名称
                  schemeNo: item.schemeNo // 计划编号
                }
              }
            })
          }
          this.getSummaries() // 预算金额总计
          this.paginData()
        }
      }).catch(() => {

      })
    },
    // 分页
    paginData() {
      this.showTenderMaterielInfoList = paging({}, this.formData.tenderMaterielInfoList, this.paginationData)// 分页功能
    },
    // 物料列表行内编辑和保存
    editRow(row, index, state) {
      const stateDate = this.showTenderMaterielInfoList[index]
      // 点击保存
      if (!state) {
        this.$refs.forms.validate((valid) => {
          if (valid) {
            saveSingleTenderMaterielInfo(row).then(res => {
              row.id = res.data.id
            }).catch(() => {
            })
            stateDate.state = false
          }
        })
      } else {
        this.$set(stateDate, 'state', true)
        // 编辑
        stateDate.state = true
      }
      this.showTenderMaterielInfoList.splice(index, 1, stateDate)
    },
    // 添加一行
    addRow() {
      const data = cloneObject(this.addData)// 深层拷贝
      this.formData.tenderMaterielInfoList.push(data)
      this.paginData()
    },
    // 删除物料
    deleteRow(index, row) {
      this.$confirm('此操作将删除该物料, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'confirmBtn',
        cancelButtonClass: 'cancelBtn',
        type: 'warning'
      }).then(() => {
        if (row.id) {
          // 有id的情况下
          const data = { id: row.id }
          removeTenderMaterielInfo(data).then(() => {
            const params = this.paginationData
            this.formData.tenderMaterielInfoList.splice(params.pageSize * (params.pageNo - 1) + index, 1)
            this.getSummaries() // 预算金额总计
            this.paginData()
          })
        } else {
          // 无id的情况下
          const params = this.paginationData
          this.formData.tenderMaterielInfoList.splice(params.pageSize * (params.pageNo - 1) + index, 1)
          this.getSummaries() // 预算金额总计
          this.paginData()
        }
      }).catch(() => {
      })
    },
    // 上一步
    prevStep() {
      // router携带参数
      const pathData = {
        id: this.$route.params.id
      }
      this.$emit('stepPage', 'prev', pathData)// 步骤条切换方法 prev 上一步
    },
    /*
    * 保存数据接口 暂存，下一步
    * type参数 draft 点击步骤条切换-进行保存草稿
    * */
    saveData(type) {
      // 校验标的清单列表是否为0
      if (this.formData.tenderMaterielInfoList.length > 0) {
        this.confirmLoading = true// Loding
      } else {
        if (type === 'draft') return false // 判断是否-点击步骤条切换-如果是则不执行提示
        this.$message({
          message: '标的物清单不能为空',
          type: 'warning'
        })
        return
      }
      // 进行排序
      this.formData.tenderMaterielInfoList.forEach((item, index) => {
        item.sortNo = index + 1// 排序
      })
      saveTenderMaterielInfo(this.formData.tenderMaterielInfoList).then(() => {
        // router携带参数
        const pathData = {
          id: this.$route.params.id// 项目Id
        }
        this.confirmLoading = false

        if (type === 'draft') return false// 判断是否-点击步骤条切换-如果是则不执行next下一步
        this.$emit('stepPage', 'next', pathData)// 步骤条切换方法 next下一步
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    //  下一步
    nextStep() {
      this.$refs.forms.validate((valid) => {
        if (valid) {
          this.saveData()
        }
      })
    },
    // 模板上传成功时触发
    handleSuccess(response) {
      if (response.header.ret === '0') {
        this.$message.success('导入成功')
        this.initData() // 调用查询项目物料列表
        this.getSummaries() // 预算金额总计
      } else {
        this.$message.error(response.header.msg)
      }
      this.$refs.upload.clearFiles()
    },
    // 导出物料
    exportMateriel() {
      const data = {
        tenderId: this.queryMaterieData.tenderId, // 项目Id
        pageNo: 1,
        pageSize: 999999999
      }
      if (this.formData.tenderMaterielInfoList.length > 0) {
        exportMaterielList(data).then(res => {
          download(res, '物料信息.xls')
        })
      } else {
        this.$message.warning('物料列表为空')
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@assets/style/common/public.less';
  .inline-file {
    color: @blue;

  }
  /deep/.el-form-item--small.el-form-item{
    margin: 0;
  }
  .summaries{
    margin-right: 10px;
  }
</style>

