<template>
  <div class="change-price">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >

      <cy-info-title style="margin: 0px -15px 10px;"> 基础信息 </cy-info-title>
      <el-form-item label="项目名称" prop="businessNumber">
        <el-select v-model="ruleForm.businessNumber" style="width: 100%" placeholder="请选择项目名称" disabled @change="selectProject">
          <el-option
            v-for="(item, index) in businessList"
            :key="index + '_business'"
            :label="item.projectName"
            :value="item.businessNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="核心企业名称">
        <el-input v-model="businessInfo.coreEnterpriseName" disabled />
      </el-form-item>
      <el-form-item label="供应商（主体）名称">
        <el-input v-model="businessInfo.mainEnterpriseName" disabled />
      </el-form-item>
      <el-form-item label="贸易平台">
        <el-input v-model="businessInfo.platformName" disabled />
      </el-form-item>
      <el-form-item label="业务编号">
        <el-input :value="businessInfo.businessNumber" disabled />
      </el-form-item>
      <el-form-item label="预估结算日期" prop="expectedSettlementDate">
        <el-date-picker v-model="ruleForm.expectedSettlementDate" value-format="yyyy-MM-dd" type="date" placeholder="选择预估结算日期" style="width: 100%;" disabled />
      </el-form-item>

      <el-form-item label="验收经办人（供应商）" prop="checkOperatorSupplier">
        <el-select v-model="ruleForm.checkOperatorSupplier" style="width: 100%" placeholder="请输入验收经办人（供应商）" @change="chooseSuplierPerson">
          <el-option
            v-for="(item, index) in suplierPersonList"
            :key="index + '_suplier'"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>

      <!--  货物信息（下游验收） -->
      <cy-info-title style="margin: 25px -15px 0;">
        <span>
          货物信息（下游验收）
          <span class="statistics">数量合计： <span>{{ countTotal }}</span></span>
          <span class="statistics">销售总价合计： <span>{{ priceTotal }}</span></span>
        </span>
        <div slot="right">
          <el-button type="text" @click="downLoadTemplate">下载模板</el-button>
          <el-button type="text" @click="importTemplate">模板导入</el-button>
          <el-button type="text" @click="clearGoods">清空</el-button>
          <input ref="fileButton" type="file" accept="xls, .xlsx, .excel" style="display: none" @change="importFile">
        </div>
      </cy-info-title>
      <div style="width: 100%;margin: 0 -15px;">
        <cy-comm-table
          ref="commTable"
          :columns="columns"
          :data="goodsInfoList"
          :count="0"
        />
      </div>

      <cy-info-title style="margin: 25px -15px 10px;">补充说明</cy-info-title>
      <el-form-item label=" 补充说明" class="two-form-item" prop="supplementDescription">
        <el-input
          v-model="ruleForm.supplementDescription"
          placeholder="请输入单价调整说明"
        />
      </el-form-item>
      <el-form-item label="补充说明文件" prop="acceptanceAdjustFile">
        <cy-upload
          ref="acceptanceAdjustFile"
          :upload-params="{fileType: 'acceptanceAdjustFile'}"
          :file-data="ruleForm.acceptanceAdjustFile"
          :upload-from-orange-status="true"
          placeholder="请上传加盖公章的调价说明函"
        />
      </el-form-item>

    </el-form>

    <div class="submit-btn">
      <el-button @click="closePage">关闭</el-button>
      <el-button type="primary" @click="validate('submit')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { exportFile } from '@/utils/index'
import { getDetails, getAdjustDetails, getOperaterOfCore, getCompletedProjectList, getCompletedProjectDetail, acceptanceAdjust, downloadAdjust, importGoodsTemplate } from '@/api/myTrade/acceptanceManagement/index'
export default {
  name: 'ChangePrice',
  components: {

  },
  data() {
    return {
      ruleForm: {
        projectName: '',
        businessNumber: '',
        expectedSettlementDate: '',
        checkOperatorSupplier: '',
        checkOperatorSupplierContact: '',
        supplementDescription: '',
        acceptanceAdjustFile: []
      },
      rules: {
        checkOperatorSupplier: [{ required: true, trigger: 'blur', message: '请输入验收经办人（供应商）' }],
        supplementDescription: [{ required: true, trigger: 'blur', message: '请输入补充说明' }]
      },
      countTotal: 0,
      priceTotal: 0,
      businessList: [],
      businessInfo: {
        projectName: '',
        coreEnterpriseName: '',
        mainEnterpriseName: '',
        platformName: '',
        businessNumber: ''

      },
      suplierPersonList: [],
      suplierPersonInfo: {},
      goodsInfoList: [

      ],
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '名称',
          showTooltip: true,
          prop: 'goodsName'
        },
        {
          label: '材质',
          showTooltip: true,
          prop: 'goodsMaterial'
        },
        {
          label: '型号',
          showTooltip: true,
          prop: 'goodsType'
        },
        {
          label: '厂家',
          showTooltip: true,
          prop: 'goodsFactory'
        },
        {
          label: '单位',
          showTooltip: true,
          prop: 'goodsUnit'
        },
        {
          label: '数量',
          showTooltip: true,
          prop: 'goodsQuantity'
        },
        {
          label: '参考价格',
          showTooltip: true,
          prop: 'referencePrice'
        },
        {
          label: '浮动价格',
          showTooltip: true,
          prop: 'floatingPrice'
        },
        {
          label: '销售单价（元）',
          showTooltip: true,
          prop: 'salesPrice'
        },
        {
          label: '验收日期',
          showTooltip: true,
          prop: 'acceptanceDate'
        }
        // {
        //   label: '操作',
        //   show: true,
        //   render: (h, row, index) => {
        //     const btnList = [
        //       { msg: '删除', icon: 'el-icon-delete', power: 'projectNumber:empty', category: 'clear' }
        //     ]
        //     const options = btnList.map(item => {
        //       return (
        //         <span class='table-icon-box' style='font-size: 14px;' onClick={() => { this.deleteGoods(index) }}>
        //           { item.msg }
        //         </span>
        //       )
        //     })
        //     return <div>{ options }</div>
        //   }

        // }
      ],
      detailInfos: {}
    }
  },
  watch: {
    goodsInfoList: {
      handler(newV) {
        let num = 0; let price = 0
        this.goodsInfoList.forEach(item => {
          num += Number(item.goodsQuantity)
          price += Number(item.salesPrice) * Number(item.goodsQuantity)
          item.acceptanceDate = item.acceptanceDate.split(' ')[0]
        })

        this.countTotal = num ? num.toFixed(4) : 0
        this.priceTotal = price ? price.toFixed(2) : 0
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.getPojectList()
    this.getDetailInfo()
  },
  methods: {
    getDetailInfo() {
      const { id } = this.$route.query
      if (this.$route.query.taskName) { // 退回的单价调整
        getAdjustDetails({ id: id }).then(res => {
          if (res.success) {
            const { data } = res
            this.detailInfos = data
            this.ruleForm.businessNumber = data.businessNumber
            this.selectProject(data.businessNumber)

            for (const k in this.ruleForm) {
              if (data[k] !== '' && data[k] !== null && data[k] !== undefined) {
                this.ruleForm[k] = data[k]
              }
            }

            this.goodsInfoList = data.priceGoodsInfoList
            // this.goodsInfoList.map(item => {
            //   item.goodsId = item.id
            // })
            this.ruleForm.acceptanceAdjustFile = data.fileList
          }
        })
      } else { // 首次调整
        getDetails({ id: id }).then(res => {
          if (res.success) {
            const { data } = res
            this.detailInfos = data
            this.ruleForm.businessNumber = data.businessNumber
            this.selectProject(data.businessNumber)

            for (const k in this.ruleForm) {
              if (data[k] !== '' && data[k] !== null && data[k] !== undefined) {
                this.ruleForm[k] = data[k]
              }
            }

            this.goodsInfoList = data.acceptanceGoodInfos
            this.goodsInfoList.map(item => {
              item.goodsId = item.id
            })
          }
        })
      }
    },

    validate(submitType) {
      const acceptanceAdjustFile = this.$refs.acceptanceAdjustFile.getFileLists

      // 货物
      const priceGoodsInfoList = []
      this.goodsInfoList.map(item => {
        const obj = {
          goodsId: Number(item.goodsId),
          goodsName: item.goodsName,
          goodsMaterial: item.goodsMaterial,
          goodsType: item.goodsType,
          goodsFactory: item.goodsFactory,
          goodsUnit: item.goodsUnit,
          goodsQuantity: item.goodsQuantity,
          acceptanceDate: item.acceptanceDate,
          salesPrice: item.salesPrice,
          referencePrice: item.referencePrice,
          floatingPrice: item.floatingPrice
        }
        priceGoodsInfoList.push(obj)
      })
      const fileIds = []
      acceptanceAdjustFile.map(item => {
        fileIds.push(item.id)
      })

      // 人员信息
      this.suplierPersonInfo = this.suplierPersonList.filter(item => item.name === this.ruleForm.checkOperatorSupplier)[0]

      var params = {
        Loading: true,
        cAcceptanceBasicInfoId: this.$route.query.id,
        supplementDescription: this.ruleForm.supplementDescription,
        checkOperatorSupplier: this.ruleForm.checkOperatorSupplier,
        mobile: this.detailInfos.checkOperatorSupplierContact || this.suplierPersonInfo.mobile,
        priceGoodsInfoList,
        fileIds
      }
      if (this.ruleForm.checkOperatorSupplier !== this.detailInfos.checkOperatorSupplier) {
        params.cAcceptancePersonInfo = this.suplierPersonInfo
        // params.checkOperatorSupplier = this.ruleForm.checkOperatorSupplier
        // params.mobile = this.ruleForm.checkOperatorSupplierContact
      }
      if (this.$route.query.taskName) {
        params.id = this.detailInfos.id
      }

      if (submitType === 'temp') {
        this.submit(params, submitType)
      } else if (submitType === 'submit') {
        this.$refs.ruleFormRef.validate(valid => {
          if (valid) {
            if (priceGoodsInfoList.length === 0) {
              this.$message.warning('货物信息不能为空')
              return
            }
            if (!acceptanceAdjustFile.length) {
              this.$message.warning('请上传补充说明文件')
              return
            }
            console.log(params)
            this.submit(params, submitType)
          } else {
            this.$message.warning('必填项不能为空')
          }
        })
      }
    },
    submit(data, submitType) {
      acceptanceAdjust(data).then((res) => {
        if (res.success) {
          if (submitType === 'submit') {
            this.$message.success('提交成功')
            this.closePage()
          } else {
            this.$message.success('暂存成功')
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },

    // 货物-模板导入
    importTemplate() {
      this.$refs.fileButton.click()
    },
    importFile(e) {
      const file = e.target.files[0] || e.dataTransfer.files[0]// 用于提交
      const postData = new FormData()
      const { id } = this.$route.query
      postData.append('acceptanceBasicId', id)
      postData.append('flag', 1)
      postData.append('file', file)
      importGoodsTemplate(postData).then(res => {
        if (res.success && res.data.length) {
          this.goodsInfoList = []
          res.data.map(item => {
            item.salesPrice = parseFloat(item.referencePrice + item.floatingPrice).toFixed(2)
            item.acceptanceDate = item.acceptanceDate.split(' ')[0]
            this.goodsInfoList.push(item)
          })
        }
      })
      e.target.value = ''
    },

    // 清空货物
    clearGoods() {
      this.goodsInfoList = []
      this.countTotal = 0
      this.priceTotal = 0
    },

    // 查询完成项目-项目名称
    getPojectList() {
      getCompletedProjectList().then(({ data }) => {
        this.businessList = data || []
      })
    },

    // 项目具体信息
    selectProject(v) {
      if (this.ruleForm.businessNumber) {
        getCompletedProjectDetail({ businessNumber: v }).then((res) => {
          if (res.success) {
            const { data } = res
            for (const k in this.businessInfo) {
              if (data[k] !== '' && data[k] !== null && data[k] !== undefined) {
                this.businessInfo[k] = data[k]
              }
            }
          }
        })
        this.getPersonCore(v)
      }
    },

    // 获取经办人（核心企业）
    getPersonCore(v) {
      const params = {
        businessNumber: v
      }
      getOperaterOfCore(params).then(({ data }) => {
        if (data.length) {
          this.corePersonList = data.filter(item => {
            return item.type === '验收经办人（核心企业）'
          })

          this.suplierPersonList = data.filter(item => {
            return item.type === '验收经办人（供应商）'
          })
        } else {
          this.corePersonList = []
          this.suplierPersonList = []
        }
      })
    },

    // 选择供应商验收人
    chooseSuplierPerson(v) {
      const suplierPersonInfo = this.suplierPersonList.filter(item => item.name === this.ruleForm.checkOperatorSupplier)[0]
      this.ruleForm.checkOperatorSupplierContact = suplierPersonInfo.mobile
    },

    // 下载
    downLoadTemplate() {
      const { id } = this.$route.query
      downloadAdjust({ id: id }).then((data) => {
        exportFile(data)
      })
      return
    },

    // 删除货物
    deleteGoods(index) {
      if (this.goodsInfoList.length) {
        this.goodsInfoList.splice(index, 1)
      }
    },

    closePage() {
      this.$router.push({
        name: 'MyTrade',
        query: {
          type: 'AcceptanceManagement'
        }
      })
    }
  }
}
</script>

  <style lang="scss" scoped>
  .change-price {
    padding: 10px 30px;
    .statistics {
      color: #FF0000;
      margin-left: 20px;
      font-size: 14px;
    }
    .tips {
      color: #918c8c;
      font-size: 12px;
    }
    .required-item {
      .required-label:before {
        content: '*'!important;
        color: #F56C6C;
        margin-right: 4px;
      }

    }
  }
  </style>
