<template>
  <div>
    <div class="form-content" v-loading="loading">
      <el-form
        ref="formInfo"
        :model="parameter"
        label-width="100px"
        label-position="right"
      >
        <div class="rows" @click="handleOver">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">基本信息</div>
          </div>
          <i
            :class="!flexAuto ? 'el-icon-arrow-right' : 'el-icon-arrow-down'"
            style="margin-left: 10px"
          ></i>
        </div>
        <div :class="!flexAuto ? 'auto' : 'classNone'">
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="申请编号" prop="applicationNum">
                <el-input
                  disabled
                  v-model="parameter.applicationNum"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请类型" prop="applicationType">
                <dict-select
                  dictCode="cgsq-sqlx"
                  :hasDefaultOption="true"
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  @select="changeApplicationType"
                  v-model="parameter.applicationType"
                  placeholder="请选择申请类型"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="需求日期" prop="applicationDate">
                <el-date-picker
                  style="width: 100%"
                  v-model="parameter.applicationDate"
                  value-format="yyyy-MM-dd"
                  @change="changeApplicationDate"
                  type="date"
                  :disabled="currentNode == 1 ? false : true"
                  placeholder="选择需求日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="定价方式" prop="procurementMethod">
                <dict-select
                  dictCode="cgsq-djfs"
                  :disabled="currentNode == 1 ? false : true"
                  :hasDefaultOption="true"
                  clearable
                  style="width: 100%"
                  v-model="parameter.procurementMethod"
                  placeholder="请选择定价方式"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6"
              ><el-form-item label="是否集中采购" prop="matIfPlat">
                <dict-select
                  dictCode="cglx-ywlx"
                  :hasDefaultOption="true"
                  clearable
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  v-model="parameter.matIfPlat"
                  placeholder="请选择是否集中采购"
                /> </el-form-item
            ></el-col>
            <el-col :span="6">
              <el-form-item label="报价方式" prop="isTax">
                <dict-select
                  dictCode="cgsq-bjfs"
                  :hasDefaultOption="true"
                  clearable
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  v-model="parameter.isTax"
                  placeholder="请选择报价方式"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否代采" prop="isAgencyProcure">
                <dict-select
                  dictCode="cgsq-sfdc"
                  :hasDefaultOption="true"
                  clearable
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  @select="changeProcure"
                  v-model="parameter.isAgencyProcure"
                  placeholder="请选择是否代采"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="parameter.isAgencyProcure == 1">
              <el-form-item label="代采企业" prop="agencyProcureOrgName">
                <el-input
                  v-model="parameter.agencyProcureOrgName"
                  disabled
                  placeholder=""
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款方式" prop="payMethod">
                <dict-select
                  dictCode="cglx-fkfs"
                  :hasDefaultOption="true"
                  clearable
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  v-model="parameter.payMethod"
                  placeholder="请选择付款方式"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="parameter.payMethod == 2">
              <el-form-item
                label="承兑时间"
                key="1"
                class="form-flex"
                prop="acceptanceTime"
              >
                <dict-select
                  dictCode="cdsj"
                  :hasDefaultOption="true"
                  clearable
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  @select="changeAcceptanceTime"
                  v-model="parameter.acceptanceTime"
                  placeholder="请选择承兑时间"
                />
                <div class="append">月</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="挂账时间"
                class="form-flex"
                prop="pendingTime"
              >
                <div
                  slot="label"
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                  "
                >
                  <span>挂账时间</span>
                  <el-tooltip
                    effect="dark"
                    content="挂账时间为0表示无时间限制"
                    placement="bottom"
                  >
                    <i style="font-size: 18px" class="el-icon-question" />
                  </el-tooltip>
                </div>
                <dict-select
                  dictCode="cdsj"
                  :hasDefaultOption="true"
                  clearable
                  :disabled="currentNode == 1 ? false : true"
                  style="width: 100%"
                  @select="changePendingTime"
                  v-model="parameter.pendingTime"
                  placeholder="请选择挂账时间"
                />
                <div class="append">月</div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="是否公示"
                prop="isAnnouncement"
                v-if="this.parameter.procurementMethod == 5"
              >
                <el-select
                :disabled="currentNode == 1 ? false : true"
                  v-model="parameter.isAnnouncement"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in announcementList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">相关文件</div>
            </div>
          </div>
          <div v-if="currentNode==1">
            <el-upload
              class="upload-demo"
              ref="upload"
              :headers="headers"
              :action="action"
              :file-list="dataList"
              :multiple="false"
              accept=".png,.jpg,.jpeg,.xlsx,.xls,.pdf,.docx,.doc,.zip,.rar"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
            >
              <el-button
                icon="el-icon-upload"
                slot="trigger"
                size="small"
                type="primary"
                >上传文件</el-button
              >
              <span>（请上传相关技术文件、招标文件）</span>
            </el-upload>
          </div>
          <el-table
            class="down"
            :data="dataList"
            border
            stripe
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column prop="name" label="文件名称"></el-table-column>
            <el-table-column prop="size" label="文件大小">
              <template slot-scope="scope">
                <span>{{ scope.row.fileSize }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="上传时间">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.createTime }}
                </div>
              </template>
            </el-table-column>
            <el-table-column width="150px" label="操作">
              <template slot-scope="scope">
                <el-button size="small" type="text">
                  <a
                    target="_blank"
                    @click="downloadFile(scope.row.name, scope.row.url)"
                    >下载</a
                  >
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <el-form ref="formInfo" class="form-content1" :model="parameter">
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title" style="display: flex; align-items: center">
            <div class="text-overflow">物料信息</div>
            <el-button
              @click="openDialog"
              type="primary"
              style="margin-left: 10px"
              size="small"
              v-if="currentNode==1"
              icon="el-icon-plus"
              >添加</el-button
            >
          </div>
        </div>
        <div class="common-table-content btn-pagenation" ref="tableContent">
          <el-table
            ref="singleTable"
            class="table"
            :data="parameter.detailsList"
            style="width: 100%"
            :max-height="tableHeight"
            highlight-current-row
            :cell-style="{'text-align': 'center'}"
            :header-cell-style="{'text-align': 'center'}"
          >
            <el-table-column fixed type="index" width="55" label="序号" />

            <el-table-column
              label="企业物料编号"
              min-width="120"
              show-overflow-tooltip
              prop="matCode"
            >
            </el-table-column>
            <el-table-column
              label="平台物料编号"
              min-width="120"
              show-overflow-tooltip
              prop="matPlatcode"
            >
            </el-table-column>
            <el-table-column
              label="物料名称"
              show-overflow-tooltip
              min-width="110"
              prop="matName"
            >
            </el-table-column>
            <el-table-column
              label="物料牌号"
              min-width="110"
              show-overflow-tooltip
              prop="matMaterial"
            ></el-table-column>
            <el-table-column
              label="规格型号"
              show-overflow-tooltip
              min-width="130"
              prop="matSpec"
            >
            </el-table-column>
            <el-table-column
              label="规格型号"
              show-overflow-tooltip
              min-width="130"
              prop="matSpec"
            >
            </el-table-column>
            <el-table-column
              label="计量单位"
              show-overflow-tooltip
              min-width="80"
              prop="matUnit"
            >
            </el-table-column>
            
            <el-table-column
              label="数量"
              min-width="110"
              prop="matNum"
              show-overflow-tooltip
            >
              <template slot="header">
                <span class="required">*</span>数量
              </template>
              <template slot-scope="scope">
                  <el-input
                  v-if="currentNode == 1"
                    clearable
                    type="Number"
                    :min="0"
                    v-model="scope.row.matNum"
                    placeholder="数量"
                  ></el-input>
                  <span v-else>{{
                    scope.row.matNum
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="最高限价(元)"
              min-width="120"
              prop="maximumPriceLimit"
            >
              <template slot="header">
                <!-- 表头名称 -->
                <div style="display: flex; align-items: center">
                  <span>最高限价(元)</span>
                  <el-tooltip class="item" effect="dark" placement="top">
                    <i class="el-icon-question" style="font-size: 16px"></i>
                    <!-- 悬停提示内容 -->
                    <div slot="content">
                      <div>单价最高限价，为0表示不限价</div>
                    </div>
                  </el-tooltip>
                </div>
              </template>
              <template slot-scope="scope">
                <el-input
                  type="Number"
                  v-if="currentNode == 1"
                  v-model="scope.row.maximumPriceLimit"
                  placeholder="最高限价"
                ></el-input>
                <div v-else>{{ scope.row.maximumPriceLimit }}</div>
              </template>
            </el-table-column>
            <el-table-column label="需求日期" min-width="130" prop="demandDate">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.demandDate"
                  type="date"
                  v-if="currentNode == 1"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择需求日期"
                  style="width: 100%"
                />
                <div v-else>{{ scope.row.demandDate }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="计划编号"
              show-overflow-tooltip
              min-width="160"
              prop="planCode"
            >
              <template slot-scope="scope">
                <el-input
                v-if="currentNode == 1"
                  v-model="scope.row.planCode"
                  placeholder="计划编号"
                ></el-input>
                <div v-else>{{scope.row.planCode }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="送货地址"
              min-width="180"
              show-overflow-tooltip
              prop="unloadAddress"
            >
              <template slot="header">
                <span class="required">*</span>送货地址
              </template>
              <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.unloadAddress"
                    v-if="currentNode == 1"
                    @focus="openAddress(scope.$index)"
                    placeholder="请选择送货地址"
                    clearable
                    prefix-icon="el-icon-search"
                  ></el-input>
                  <div v-else>{{ scope.row.unloadAddress }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="企业补充说明"
              min-width="180"
              show-overflow-tooltip
              prop="remarks"
            >
              <template slot-scope="scope">
                <el-tooltip
                  width="250"
                  v-if="currentNode == 1"
                  placement="top-start"
                  effect="light"
                  :content="scope.row.remarks"
                >
                  <el-input
                    clearable
                   
                    :title="scope.row.remarks"
                    v-model="scope.row.remarks"
                    placeholder="请输入企业补充说明"
                  ></el-input>
                </el-tooltip>
                <div v-else></div>
              </template>
            </el-table-column>
            <el-table-column
              label="品牌/产地"
              show-overflow-tooltip
              min-width="100"
              prop="matBrand"
            >
            </el-table-column>
            <el-table-column
              label="基础扩展"
              show-overflow-tooltip
              min-width="140"
              prop="matBaseExt"
            >
            </el-table-column>
            <el-table-column
              label="其他扩展"
              show-overflow-tooltip
              min-width="140"
              prop="matOtherExt"
            >
            </el-table-column>
            <el-table-column label="税率" min-width="80" prop="taxRate">
            </el-table-column>

            <el-table-column
              label="挂账时间"
              min-width="100"
              prop="pendingTime"
            >
            </el-table-column>
            <el-table-column
              v-if="parameter.payMethod == 2"
              label="承兑时间"
              min-width="100"
              prop="acceptanceTime"
            >
            </el-table-column>

            <el-table-column
              fixed="right"
              align="right"
              label="操作"
              v-if="currentNode == 1"
              width="90px"
              :index="999"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  circle
                  icon="el-icon-close"
                  @click="delTable(scope.$index, scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <!-- 物料明细 -->
    <purchaseMaterial
      @addDetail="addDetail"
      :useOrgList="methodUnitsList"
      ref="troubleshooting"
    />
  </div>
</template>

<script>
import {helper} from '../../../public/hotent.helper.js'
import req from '@/request.js'
import utils from '@/hotent-ui-util.js'
import purchaseMaterial from './components/purchaseMaterial.vue'
import {mapState} from 'vuex'
export default {
  components:{
    purchaseMaterial
  },
  data() {
    return {
      parameter: {},
      loading: false,
      flexAuto: true,
      dataList: [],
      saveFlag: true,
      announcementList: [
        {
          label: '否',
          value: 0,
        },
        {
          label: '是',
          value: 1,
        },
      ],
      methodUnitsList:[],
      currentNode: 1,
    }
  },
  computed: {
    ...mapState({
      headers: (state) => {
        return {Authorization: `Bearer ${state.login.currentUser.token}`}
      },
      action: function () {
        return window.context.portal + '/biz/universal/v1/minioUpload'
      },
    }),
  },
  mounted() {
    this.currentNode = this.$route.query.node
    window.saveData = this.saveData
    window.relationData = this.relationData
    this.id = utils.getUrlKey('id')
    this.node = utils.getUrlKey('node')
    if (this.id) {
      req
        .post(
          window.context.portal +
            '/purchasingApplication/v1/selectOne?id=' +
            this.id
        )
        .then((res) => {
          if (res.data.value) {
            this.parameter = res.data.value
            if (
              this.parameter.accessoryList &&
              this.parameter.accessoryList.length != 0
            ) {
              this.dataList = this.parameter.accessoryList
            }
          }
        })
    }
  },
  methods: {
    // 修改需求日期
    changeApplicationDate(val) {
      this.parameter.applicationDate = val
      if (this.parameter.detailsList.length != 0) {
        this.parameter.detailsList.forEach((item) => {
          item.demandDate = this.parameter.applicationDate
        })
      }
    },
    changeApplicationType(val) {
      this.parameter.applicationType = val
      if (val == 2) {
        if (this.parameter.detailsList.length != 0) {
          this.parameter.detailsList.forEach((item) => {
            item.matNum = 1
          })
        }
      } else {
        if (this.parameter.detailsList.length != 0) {
          this.parameter.detailsList.forEach((item) => {
            item.matNum = ''
          })
        }
      }
    },
    changeProcure(val) {
      if (val == 0) {
        this.parameter.agencyProcureOrgName = ''
        this.parameter.agencyProcureOrgCode = ''
        this.parameter.agencyProcureOrgId = ''
      }
      if (val == 1) {
        this.parameter.agencyProcureOrgName = '重庆盛普物资有限公司'
        this.parameter.agencyProcureOrgCode = '00001513'
        this.parameter.agencyProcureOrgId = '1575018828683939840'
      }
    },
    changeAcceptanceTime(val) {
      this.parameter.acceptanceTime = val
      this.parameter.detailsList.forEach((item) => {
        item.acceptanceTime = val
      })
    },
    addDetail(list) {
      console.log(list, 'llll')
      if (this.parameter.detailsList.length == 1) {
        this.parameter.detailsList = list
        this.parameter.detailsList.forEach((item, index) => {
          item['matId'] = item.id
          item.demandDate = this.parameter.applicationDate
          item['pendingTime'] = this.parameter.pendingTime
          item['acceptanceTime'] = this.parameter.acceptanceTime
          item.preparedDate = this.dateTime
          item['maximumPriceLimit'] = 0
          item['matIfPlat'] = this.parameter.matIfPlat
          item['unloadAddress'] = ''
          item.planCode = this.parameter.applicationNum + '-' + (index + 1)
        })
      } else {
        list.forEach((item, index) => {
          this.parameter.detailsList.push({
            matName: item.matName,
            matCode: item.matCode,
            matCode: item.matCode,
            matMaterial: item.matMaterial,
            matSpec: item.matSpec,
            matNum: item.matNum,
            matUnit: item.matUnit,
            procurementMethod: item.procurementMethod,
            matBrand: item.matBrand,
            preparedDate: this.dateTime,
            demandDate: this.parameter.applicationDate,
            matBaseExt: item.matBaseExt,
            matOtherExt: item.matOtherExt,
            planCode: this.parameter.applicationNum + '-' + (index + 1),
            id: item.id,
            matPlatcode: item.matPlatcode,
            acceptanceTime: this.parameter.acceptanceTime,
            taxRate: item.matTaxrate,
            matId: item.id,
            matIfPlat: this.parameter.matIfPlat,
            maximumPriceLimit: 0,
            unloadAddress: '',
            pendingTime: this.parameter.pendingTime,
            key: new Date(),
          })
        })
      }
      if (this.parameter.applicationType == 2) {
        this.parameter.detailsList.forEach((item) => {
          item.matNum = 1
        })
      }
      this.methodUnitsList = this.parameter.detailsList
    },
    changePendingTime(val) {
      this.parameter.pendingTime = val
      this.parameter.detailsList.forEach((item) => {
        item.pendingTime = this.parameter.pendingTime
      })
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,function(file, fileList)
    handleSuccess(res, file, fileList) {
      console.log(res, fileList)
      this.dataList.push(res.value)
    },
    beforeUpload(file) {
      let acceptList = ['xlsx', 'xls','png','jpg','jpeg','xlsx','xls','pdf','docx','doc','zip','rar']
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split('.').pop().toLowerCase()
      // 判断文件格式是否符合要求
      if (acceptList.indexOf(fileType) === -1) {
        this.$message.error('请上传 .png,.jpg,.jpeg,.xlsx,.xls,pdf,.docx,.doc,.zip,.rar 格式的文件 !')
        return false
      }
    },
    //下载按钮回调
    downloadFile(name, url) {
      console.log(name, 'name')
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = name
      a.target = '_blank'
      a.href = url
      a.dispatchEvent(event)
    },
    // 删除
    deleteHandle(index) {
      this.$confirm('是否确认删除该附件', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.dataList.splice(index, 1)
      })
    },
    handleOver() {
      this.flexAuto = !this.flexAuto
    },
    //列表删除行
    delTable(index, row) {
      this.parameter.detailsList.splice(index, 1)
    },
    // 打开物料弹窗
    openDialog() {
      this.$refs.troubleshooting.add(this.parameter.matIfPlat)
    },
    /* 保存 */
    saveData() {
      if (this.saveFlag) {
        //如果是第一个节点他可以保存数据，否则不需要进行数据操作
        if (this.node == 1) {
          this.parameter.status = '2'
          this.parameter.accessoryList = this.dataList
          this.$http
            .post(
              '${portal}/purchasingApplication/v1/saveOrUpdate',this.parameter
            )
            .then((res) => {
              console.log(res, '调用结果')
              if (res.data.state) {
                this.id = res.data.value
                let params = {
                  type: 'saveData',
                  state: true,
                  businessKey: this.id, // todo 确认id字段是否正确 用接口返回值做businessKey
                  sysCode: '',
                }
                params.vars = {
                  // props1: this.forms.props1,
                  //   noticeReleaseUserAccount: this.form.noticeReleaseUserAccount,
                }
                hotent.sendMessage(params)
                this.saveFlag = false
              }
            })
        } else {
          let params = {
            type: 'saveData',
            state: true,
            businessKey: this.id, // 流程地址参数id
            sysCode: '',
          }
          hotent.sendMessage(params)
          this.isFirst = false
        }
      } else {
        let params = {
          type: 'saveData',
          state: true,
          businessKey: this.id, // 流程地址参数id
          sysCode: '',
        }
        params.vars = {
          //   noticeReleaseUserAccount: this.form.noticeReleaseUserAccount,
        }
        hotent.sendMessage(params)
        this.isFirst = false
      }
      // }
    },
    //下载按钮回调
    downloadFile(name, url) {
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.download = name
      a.target = '_blank'
      a.href = url
      a.dispatchEvent(event)
    },
    relationData(data) {
      this.loading = true
      this.$http
        .post('${portal}/purchasingApplication/v1/selectOne?id=' + data[0].id)
        .then((res) => {
          this.loading = false
          this.parameter = res.data.value
          if (
            this.parameter.accessoryList &&
            this.parameter.accessoryList.length != 0
          ) {
            this.dataList = this.parameter.accessoryList
          }
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.form-content {
  overflow-x: hidden;
}
.rows:first-of-type {
  cursor: pointer;
}
.auto {
  display: none;
}
.classNone {
  display: block;
}
.form-flex {
  /deep/.el-form-item__content {
    display: flex;
    align-items: center;
  }
}
.append {
  width: 10%;
  background-color: #f5f7fa;
  color: #909399;
  vertical-align: middle;
  display: table-cell;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 10px;
  white-space: nowrap;
  text-align: center;
}
</style>