<template>
  <div class="edit-add-detail">
    <div class="crumbs">
      <Breadcrumb
        :breadcrumbOpt="breadcrumbOpt"
        svg-name="#icon-bill"
        @breadcrumb-click="handleClose"
      />
    </div>
    <div class="form-content">
      <el-form
        ref="formInfo"
        :model="parameter"
        label-width="auto"
        label-position="right"
        :rules="rules"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">基本信息</div>
          </div>
        </div>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="订单编码" prop="orderCode">
              <el-input
                clearable
                v-model="parameter.orderCode"
                placeholder="请输入订单编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购方" prop="matCompanyName">
              <el-input
                readonly
                v-model="parameter.matCompanyName"
                placeholder="请输入采购方"
              ></el-input>
              <!-- <multipleInput
                @click="open('orgunits')"
                @delTags="(i) => deleteTags(i, 'enterpriseList')"
                :selectData="parameter.matCompanyName"
                :multiple="false"
                label="code"
                placeholder="请选择采购方"
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供货方" prop="vendorName">
              <el-input
                readonly
                @focus="open('poolUnits')"
                v-model="parameter.vendorName"
                placeholder="请选择供货方"
                prefix-icon="el-icon-search"
              ></el-input>
              <!-- <multipleInput
                @click="open('poolUnits')"
                @delTags="(i) => deleteTags(i, 'supplierList')"
                :selectData="parameter.vendorName"
                :multiple="false"
                label="code"
                placeholder="请选择供应企业"
              /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="合同" prop="contractName">
              <el-input
                v-model="parameter.contractName"
                prefix-icon="el-icon-search"
                @focus="openContract"
                placeholder="请选择合同"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不含税总金额(元)" prop="orderAmount">
              <el-input readonly v-model="parameter.orderAmount" placeholder="明细自动计算"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="含税总金额(元)" prop="taxInvalue">
              <el-input readonly v-model="parameter.taxInvalue" placeholder="明细自动计算"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24"> </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="编制时间" prop="orderCreatedate">
              <el-date-picker
                v-model="parameter.orderCreatedate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              >
              </el-date-picker>
            </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>
        <el-table
          ref="singleTable"
          :data="parameter.detailsList"
          style="width: 100%"
          highlight-current-row
          :cell-style="{'text-align': 'center'}"
          :header-cell-style="{'text-align': 'center'}"
          class="wuliao"
        >
          <el-table-column fixed type="index" width="55" label="序号" />
          <el-table-column
            label="企业物料编号"
            min-width="100"
            show-overflow-tooltip
            prop="matCode"
          >
          </el-table-column>
          <el-table-column
            label="平台物料编号"
            min-width="100"
            show-overflow-tooltip
            prop="matPlatcode"
          >
          </el-table-column>
          <el-table-column
            label="物料名称"
            min-width="100"
            show-overflow-tooltip
            prop="matName"
          >
          </el-table-column>
          <el-table-column
            label="物料牌号"
            min-width="100"
            show-overflow-tooltip
            prop="matMaterial"
          >
          </el-table-column>
          <el-table-column
            label="规格型号"
            min-width="100"
            show-overflow-tooltip
            prop="matSpec"
          >
          </el-table-column>
          <el-table-column
            label="计划编号"
            min-width="100"
            show-overflow-tooltip
            prop="planCode"
          >
          </el-table-column>
          <el-table-column
            label="计量单位"
            min-width="100"
            show-overflow-tooltip
            prop="matUnit"
          >
          </el-table-column>
          <el-table-column
            label="预计数量"
            min-width="100"
            show-overflow-tooltip
            prop="matNum"
          >
          </el-table-column>
          <el-table-column
            label="基础扩展"
            min-width="100"
            show-overflow-tooltip
            prop="matBaseExt"
          >
          </el-table-column>
          <el-table-column
            label="其他扩展"
            min-width="100"
            show-overflow-tooltip
            prop="matOtherExt"
          >
          </el-table-column>
          <el-table-column
            label="送货地址"
            min-width="100"
            show-overflow-tooltip
            prop="unloadAddress"
          >
          </el-table-column>
          <el-table-column
            label="企业补充说明"
            min-width="120"
            prop="remarks"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="供货方补充说明"
            min-width="120"
            prop="vendorNote"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="挂账时间"
            min-width="100"
            show-overflow-tooltip
            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
            label="含税单价(元)"
            min-width="120"
            show-overflow-tooltip
            prop="taxInprice"
          >
          </el-table-column>
          <el-table-column
            label="含税金额(元)"
            show-overflow-tooltip
            min-width="90"
            prop="taxInvalue"
          >
          </el-table-column>
          <el-table-column
            label="不含税单价(元)"
            min-width="120"
            show-overflow-tooltip
            prop="orderPrice"
          >
          </el-table-column>
          <el-table-column
            label="不含税金额(元)"
            min-width="110"
            show-overflow-tooltip
            prop="orderAmount"
          >
          </el-table-column>
          <el-table-column
            label="税率(%)"
            show-overflow-tooltip
            min-width="80"
            prop="taxRate"
          >
          </el-table-column>
          <el-table-column
            label="税额(元)"
            show-overflow-tooltip
            min-width="80"
            prop="taxValue"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            align="right"
            label="操作"
            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>
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button @click="handleClose">{{ $t('domestic.cancel') }}</el-button>
      <el-button type="primary" @click="handleSave">{{
        $t('domestic.save')
      }}</el-button>
    </div>
    <el-dialog
      title="合同选择"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleDialogClose"
    >
      <div class="dialog-table-search">
        <el-form
          ref="form"
          label-width="auto"
          label-position="right "
          :inline="true"
          type="flex"
          justify="left"
        >
        <el-form-item label="合同编号">
            <el-input
              size="small"
              v-model="queryParams[1].value"
              clearable
              placeholder="请输入合同编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同名称">
            <el-input
              size="small"
              v-model="queryParams[0].value"
              clearable
              placeholder="请输入合同名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="container-btn">
          <el-button
            size="small"
            icon="el-icon-search"
            type="danger"
            class="btn btn-plus"
            @click="handleSearch"
          >
            搜索
          </el-button>
          <el-button
            size="small"
            icon="el-icon-refresh-right"
            class="btn btn-plus"
            @click="clearSearchForm"
          >
            重置
          </el-button>
        </div>
      </div>
      <div class="dialog-table-single">
        <el-table
          ref="dialogTable"
          :data="dialogTableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55">
          </el-table-column>
          <el-table-column align="center" prop="contrCode" label="合同编号">
          </el-table-column>
          <el-table-column align="center" prop="contrName" label="合同名称">
          </el-table-column>
          <el-table-column align="center" prop="vendorName" label="供货方">
          </el-table-column>
          <el-table-column
            align="center"
            prop="contractAmount"
            label="合同金额(元)"
          >
          </el-table-column>

          <el-table-column align="center" prop="signData" label="签订日期">
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" :loading="saving" @click="handleDialogTableSubmit">
          保存
        </el-button>
      </span>
    </el-dialog>
    <expertOrgUnits
      @addDetail="(list) => addDetail(list, 'enterpriseList')"
      :useOrgList="enterpriseList"
      :needReturnKey="['code']"
      :multiple="false"
      title="采购方"
      ref="orgunits"
    />
    <expertPoolUnits
      @addDetail="(list) => addDetail(list, 'supplierList')"
      :useOrgList="supplierList"
      :needReturnKey="['code']"
      :multiple="false"
      title="供货方"
      ref="poolUnits"
    />
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb/index.vue'
import purchaseOrder from '@/api/BasicDataManagement/purchaseOrder.js'
import expertPoolUnits from './expertPoolUnits.vue'
import expertOrgUnits from './expertOrgUnits.vue'

export default {
  name: 'purchaseOrderAddDialog',
  components: {Breadcrumb, expertPoolUnits, expertOrgUnits},
  props: {
    editData: Object,
  },
  // mixins: [uploadMixin],
  data() {
    return {
      centralizedData: [
        {name: '是', id: 1},
        {name: '否', id: 0},
      ],
      breadcrumbOpt: [{breadcrumbName: '采购订单'}, {breadcrumbName: '新增'}],
      rules: {
        matCompanyName: [
          {
            required: true,
            message: '请选择采购方',
            trigger: 'blur',
          },
        ],
        vendorName: [
          {
            required: true,
            message: '请选择供货方',
            trigger: 'blur',
          },
        ],
        contractName: [
          {
            required: true,
            message: '请选择合同',
            trigger: 'blur',
          },
        ],
      },
      saving:false,
      parameter: {
        detailsList: [],
        orderAmount: 0,
        taxInvalue: 0,
        contractName: '',
        orderCode: '',
        contractNumber: '',
        contractId: '',
        orderCreatedate: '',
        vendorName: '',
        contractIdList:[],
        vendorId:'',
        vendorCode:''
      },
      statusList: [
        {label: '未确认', value: '1'},
        {label: '已确认', value: '2'},
      ], // 订单状态
      approvalStatusList: [
        {label: '审批中', value: '1'},
        {label: '已审批', value: '2'},
        {label: '已撤回', value: '3'},
      ], // 审批状态
      dialogVisible: false,
      dialogTableDataDetial: [],
      dialogTableData: [],
      params: {
        pageBean: {
          page: -1,
          pageSize: -1,
          total: 0,
        },
      },
      queryParams: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'contrName',
          relation: 'AND',
          value: '',
        },
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'contrCode',
          relation: 'AND',
          value: '',
        }
      ],
      enterpriseList: [],
      supplierList: [],
      selectObj: {},
      contractList: [],
      currentUser: {},
      vendorId:''
    }
  },
  created() {
    if (this.$route.query.editRows) {
      this.breadcrumbOpt[1].breadcrumbName = '编辑'
      // this.parameter = this.$route.query.editRows
      this.parameter = JSON.parse(JSON.stringify(this.$route.query.editRows))
      if (!this.parameter.detailsList) {
        this.parameter.detailsList = []
      }
    }
    this.addModifyBtn()
    let {username, userId} = JSON.parse(sessionStorage.getItem('currentUser'))
    this.currentUser = JSON.parse(sessionStorage.getItem('currentUserDetail'))
    this.parameter.matCompanyName = this.currentUser.org[0].orgName
    this.parameter.matCompanyId = this.currentUser.org[0].orgId
    this.parameter.matCompanyCode = this.currentUser.org[0].orgCode
    this.parameter.createName = username
    this.parameter.createBy = userId
    // this.getDate()
    this.getTableData()
    let moment = require('moment')
    this.parameter.orderCreatedate = moment().format('YYYY-MM-DD HH:mm:ss')
  },
  watch: {
    'parameter.detailsList': {
      handler: function (newUser, oldUser) {
        this.parameter.taxInvalue = 0
        this.parameter.orderAmount = 0
        let taxInvalue = 0
        let orderAmount = 0 
        newUser.forEach((item) => {
          taxInvalue += Number(item.taxInvalue)
          item.orderPrice = (item.taxInprice / ((item.taxRate/100)+1)).toFixed(4)
          item.orderAmount = ((Number(item.orderPrice)) * item.num).toFixed(2)
          orderAmount += Number(item.orderAmount)
        })
        this.parameter.taxInvalue = taxInvalue.toFixed(2)
        this.parameter.orderAmount = orderAmount.toFixed(2)
      },
      deep: true,
    },
  },
  mounted() {},
  methods: {
    handleSaverelease() {
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          purchaseOrder.batchSubmitstatus(this.parameter).then((res) => {
            if (res.data.state) {
              this.$message.success('保存并发布成功！')
              this.$router.go(-1)
            } else {
              this.$message.success('保存并发布失败！')
            }
          })
        }
      })
    },
    handleSelectionChange(val) {
      this.contractList = val
    },
    getDate() {
      var date = new Date()
      var year = date.getFullYear()
      var month = (1 + date.getMonth()).toString()
      month = month.padStart(2, '0')
      var day = date.getDate().toString()
      day = day.padStart(2, '0')
      this.parameter.orderCreatedate = year + '-' + month + '-' + day
    },
    getTableData() {
      this.params.querys = []
      this.params.sorter = []
      if (this.queryParams[0].value) {
        this.params.querys.push(this.queryParams[0])
      }
      if (this.queryParams[1].value) {
        this.params.querys.push(this.queryParams[1])
      }
      this.params.querys.push(
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'status',
          relation: 'AND',
          value: '3',
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'vendorId',
          relation: 'AND',
          value: this.vendorId,
        }
      )
      this.$http
        .post('${portal}/bizContract/v1/pageByOrg', this.params)
        .then((res) => {
          this.dialogTableData = res.data.value.rows
        })
    },
    getTableDataDetial(contractIdList) {
      this.params.querys = [
        {
          group: 'main',
          operation: 'IN',
          parentGroup: '',
          property: 'contractId',
          relation: 'AND',
          value: contractIdList,
        },
      ]
      this.params.sorter = []
      this.$http
        .post('${portal}/contractItem/v1/query', this.params)
        .then((res) => {
          this.dialogTableDataDetial = res.data.rows
          this.parameter.detailsList = []
      let sum = 0
      this.parameter.detailsList = this.dialogTableDataDetial
      this.parameter.detailsList.forEach((item) => {
        item.contractItemId = item.id
        item.orderCode = this.parameter.orderCode
        item.matNum = item.num
        if (item.taxInprice && item.taxValue) {
          item.orderPrice = (item.taxInprice / ((item.taxRate/100)+1)).toFixed(4)
          item.orderAmount = ((Number(item.orderPrice)) * item.num).toFixed(2)
        } else {
          item.orderPrice = 0
          item.orderAmount = 0
        }
        this.parameter.orderAmount += Number(item.orderAmount)
        sum +=  item.taxInvalue
        this.parameter.taxInvalue = sum
      })
        })
    },
    open(type) {
      this.$refs[type].add()
    },
    addDetail(list, key) {
      this.vendorId = list[0].vendorId
      if (key == 'supplierList') {
        this.parameter.vendorName = list[0].vendorName
        this.parameter.vendorId = list[0].vendorId
        this.parameter.vendorCode = list[0].vendorCode
      }
      this.$nextTick(() => {
        this.$refs.formInfo.clearValidate('vendorName')
      })
    },
    openContract() {
      this.dialogVisible = true
      this.getTableData()
    },
    handleSearch() {
      this.getTableData()
    },
    clearSearchForm() {
      this.queryParams[0].value = ''
      this.getTableData()
    },
    // 删除明细
    delTable(index, row) {
      this.parameter.detailsList.splice(index, 1)
    },
    handleDialogTableSubmit() {
      let selection = this.contractList
      this.parameter.contractIdList = selection.map(item=>{
        return item.id
      })
      this.parameter.contractName = selection.map(item=>{
        return item.contrName
      }).join(',')
      this.getTableDataDetial(this.parameter.contractIdList)
      this.dialogVisible = false
      this.$nextTick(()=>{
        this.$refs.formInfo.clearValidate('contractName')
      })
    },
    getCode() {
      this.$http
        .get('${portal}/sys/identity/v1/getNextIdByAlias?alias=cgpt_cgdd')
        .then((res) => {
          if (res.data.state) {
            this.parameter.orderCode = res.data.value
          }
        })
    },
    //编辑
    addModifyBtn() {
      if (this.$route.query.editRows) {
        this.breadcrumbOpt[1].breadcrumbName = '编辑'
        this.modifychoData(this.$route.query.editRows)
      } else {
        this.breadcrumbOpt[1].breadcrumbName = '新增'
        this.getCode()
      }
    },
    //获取修改回显数据
    modifychoData(val) {
      this.$http
        .post('${portal}/bizPurchaseOrder/v1/selectOne?id=' + val.id)
        .then((res) => {
          if (res.data.state) {
            this.parameter = res.data.value
          }
        })
    },
    // 关闭//面包屑点击
    handleClose() {
      if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
        this.$router.push({
          name: 'purchaseOrder',
          params: {
            pageBean: this.$route.query.pageBean,
          },
        })
      } else {
        this.$router.push({
          name: 'purchaseOrder',
        })
      }
      this.parameter = {}
    },
    // 保存
    handleSave() {
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          this.saving = true
          if (!this.$route.query.editRows && this.parameter.detailsList) {
            this.parameter.detailsList.forEach((item) => {
              delete item['id']
            })
          }
          purchaseOrder.batchSubmit(this.parameter).then((res) => {
            this.saving = false
            if (res.data.state) {
              this.$message.success('保存成功！')
              this.$router.go(-1)
            }
          })
        }
      })
    },

    handleDialogClose(done) {
      done()
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body {
  padding-top: 10px;
}
/deep/ .el-table thead tr th {
  background-color: #eee !important;
  border-right: 1px solid #dfe2e8 !important;
}
.dialog-table {
  padding: 10px;
  margin-top: 10px;
  border-radius: 8px 8px 8px 8px;
  background-color: #fff;
}

.dialog-table-search {
  height: 80px;
  padding: 0 20px;
  margin: 10px 0 0 0;
  border-radius: 8px 8px 8px 8px;
  background-color: #fff;
  box-sizing: border-box;
  transition: height 0.3s linear;
  display: flex;
  .container-btn {
    display: flex;
    align-items: center;
  }
}
.dialog-table-page {
  height: 50px;
  padding: 0 20px;
  margin: 10px 0 0 0;
  border-radius: 8px 8px 8px 8px;
  background-color: #fff;
  box-sizing: border-box;
  transition: height 0.3s linear;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
// /deep/.el-row {
//   padding: 0 100px;
// }
.rows {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebebeb;
  margin-bottom: 16px;
  padding: 10px 0;
  .rows-left {
    margin-right: 10px;
    .rows-hr {
      width: 3px;
      height: 18px;
      background-color: #0e6eff;
      border-radius: 2px;
    }
  }
  .rows-title {
    .text-overflow {
      width: 100%;
      font-size: 16px;
    }
  }
}
.wuliao {
  ::v-deep .el-input__inner[disabled] {
    background-color: white;
    color: black;
    cursor: not-allowed;
  }
}
</style>
