<template>
  <div class="edit-add-detail">
    <div class="crumbs">
      <Breadcrumb
        :breadcrumbOpt="breadcrumbOpt"
        svg-name="#icon-business"
        @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="isdCode">
              <el-input
                readonly
                v-model="parameter.isdCode"
                placeholder="自动申成对账单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发起单位" prop="matCompanyName">
              <el-input
                clearable
                v-model="parameter.matCompanyName"
                placeholder="请输入发起单位"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发起人" prop="matUserName">
              <el-input
                clearable
                v-model="parameter.matUserName"
                placeholder="请输入发起人"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="发起人联系方式" prop="matCompanyPhone">
              <el-input
                clearable
                type="number"
                v-model="parameter.matCompanyPhone"
                placeholder="请输入发起人联系方式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="对账单位" prop="vendorId">
              <el-select
                filterable
                clearable
                style="width: 100%"
                @change="changeContract"
                v-model="parameter.vendorId"
                placeholder="请选择对账单位"
              >
                <el-option
                  v-for="item in vendorList"
                  :key="item.vendorId"
                  :label="item.vendorName"
                  :value="item.vendorId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货单" prop="receiptId">
              <el-input
                v-model="parameter.receiptId"
                @focus="openReceipt"
                placeholder="请选择收货单"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="含税总金额" prop="totalAmount">
              <el-input
                v-model="parameter.totalAmount"
                readonly
                placeholder="由收货单自动计算"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不含税总金额" prop="amount">
              <el-input
                v-model="parameter.amount"
                readonly
                placeholder="由收货单自动计算"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合计税额" prop="taxAmount">
              <el-input
                v-model="parameter.taxAmount"
                readonly
                placeholder="由收货单自动计算"
              ></el-input>
            </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>
          <el-button
            type="primary"
            size="mini"
            style="margin-left: 15px"
            icon="el-icon-plus"
            @click="addTable"
            >添加收货明细</el-button
          >
        </div>
        <el-table
          ref="singleTable"
          :data="parameter.isdDetail"
          style="width: 100%"
          border
          highlight-current-row
          size="small"
          :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="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="80"
            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="80"
            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" prop="matUnit">
          </el-table-column>
          <el-table-column label="收货数量" min-width="130" prop="isdQuantity">
          </el-table-column>
          <el-table-column label="税率(%)" min-width="110" prop="taxRate">
          </el-table-column>
          <el-table-column
            label="含税单价(元)"
            min-width="130"
            prop="taxInprice"
          >
          </el-table-column>
          <el-table-column
            label="含税金额(元)"
            min-width="130"
            prop="taxInvalue"
          >
          </el-table-column>
          <el-table-column
            label="不含税单价(元)"
            min-width="130"
            prop="isdPrice"
          >
          </el-table-column>
          <el-table-column
            label="不含税金额(元)"
            min-width="130"
            prop="isdAmount"
          >
          </el-table-column>
          <el-table-column label="税额(元)" min-width="110" prop="taxValue">
          </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="pendingTime"
          >
          </el-table-column>
          <el-table-column
            label="收货地址"
            min-width="100"
            show-overflow-tooltip
            prop="unloadAddress"
          >
          </el-table-column>
          <el-table-column
            label="企业补充说明"
            min-width="110"
            prop="purNote"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="供货方补充说明"
            min-width="110"
            prop="vendorNote"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            align="right"
            width="90px"
            label="操作"
            :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" :loading="loadingBtn" @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[0].value"
              clearable
              placeholder="请输入发货单号"
            ></el-input>
          </el-form-item>
          <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-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>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-table-single">
        <el-table
          ref="dialogTable"
          :data="dialogTableData"
          style="width: 100%"
          border
          row-key="id"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            reserve-selection
            type="selection"
            width="55"
          >
          </el-table-column>
          <el-table-column align="center" show-overflow-tooltip prop="arrivalCode" label="发货单号">
          </el-table-column>
          <el-table-column
            align="center"
            prop="vendorName"
            show-overflow-tooltip
            label="发货公司"
          >
          </el-table-column>
          <!-- <el-table-column
            align="center"
            prop="outManifestUserName"
            label="发货人"
          >
          </el-table-column> -->
          <el-table-column
            align="center"
            prop="receiptCode"
            show-overflow-tooltip
            label="收货单号"
          >
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            prop="matCompanyName"
            label="收货公司"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="matUserName"
            label="收货人"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="receiptDate"
            label="收货时间"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="amount"
            show-overflow-tooltip
            label="金额"
          >
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="handleDialogTableSubmit">
          确定
        </el-button>
      </span>
    </el-dialog>
    <detialsDialog
      ref="detials"
      @load="getLoad"
      :useOrgList="detailList"
    ></detialsDialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb/index.vue'
import reconciliationManagement from '@/api/BasicDataManagement/reconciliationManagement.js'
import detialsDialog from './detialsDialog.vue'
export default {
  name: 'statementManagementAddDialog',
  components: {Breadcrumb, detialsDialog},
  props: {
    editData: Object,
  },
  data() {
    return {
      breadcrumbOpt: [{breadcrumbName: '对账单管理'}, {breadcrumbName: '新增'}],
      rules: {
        receiptId: [
          {
            required: true,
            message: '请选择收货单',
            trigger: 'blur',
          },
        ],
        matUserName: [
          {
            required: true,
            message: '请输入发起人',
            trigger: 'blur',
          },
        ],
        matCompanyPhone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur',
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号码格式不正确',
            trigger: 'blur',
          },
        ],
        isdCode: [
          {
            required: true,
            message: '请输入账单编号',
            trigger: 'blur',
          },
        ],
        vendorId: [
          {
            required: true,
            message: '请选择对账单位',
            trigger: 'blur',
          },
        ],
        matCompanyName: [
          {
            required: true,
            message: '请输入发起单位',
            trigger: 'blur',
          },
        ],
      },
      parameter: {
        isdCode: '',
        amount: 0,
        totalAmount: 0,
        taxAmount: 0,
        matCompanyName: '',
        matCompanyId: '',
        matCompany: '',
        matCompanyPhone: '',
        vendorName: '',
        vendorId: '',
        vendorCode: '',
        receiptCode: '',
        receiptId: '',
        isdDetail: [],
        status: '1',
      },
      dialogVisible: false,
      loadingBtn: false,
      dialogTableData: [],
      detailList: [],
      params: {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
      },
      queryParams: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'arrivalCode',
          relation: 'AND',
          value: '',
        },
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: 'vendorName',
          property: '',
          relation: 'AND',
          value: '',
        },
      ],
      selectObj: {},
      oldDetailslist: [],
      receiptList: [],
      vendorList: [],
    }
  },
  created() {
    this.addModifyBtn()
    if (this.$route.query.editRows) {
      this.breadcrumbOpt[1].breadcrumbName = '编辑'
      let row = JSON.parse(JSON.stringify(this.$route.query.editRows))
      this.selectOne(row)
    }
    let userDetail = JSON.parse(sessionStorage.getItem('currentUserDetail'))
    let {fullname, userId, mobile} = userDetail.user
    this.parameter.matUserName = fullname
    this.parameter.matUserId = userId
    this.parameter.matCompanyPhone = mobile
    this.parameter.matCompany = userDetail.org[0].orgCode
    this.parameter.matCompanyId = userDetail.org[0].orgId
    this.parameter.matCompanyName = userDetail.org[0].orgName
    this.getOutCompany()
  },
  watch: {
    'parameter.isdDetail': {
      handler: function (newUser, oldUser) {
        this.parameter.totalAmount = 0
        this.parameter.taxAmount = 0
        this.parameter.amount = 0
        let taxAmount = 0
        let totalAmount = 0
        let amount = 0
        newUser.forEach((item) => {
          totalAmount += Number(item.taxInvalue)
          taxAmount += Number(item.taxValue)
          amount += (Number(item.amount)||Number(item.isdAmount))
        })
        this.parameter.totalAmount = totalAmount.toFixed(2)
        this.parameter.taxAmount = taxAmount.toFixed(2)
        this.parameter.amount = amount.toFixed(2)
      },
      deep: true,
    },
  },
  mounted() {},
  methods: {
    getCode() {
      this.$http
        .get('${portal}/sys/identity/v1/getNextIdByAlias?alias=dzgl_dzdh')
        .then((res) => {
          if (res.data.state) {
            this.parameter.isdCode = res.data.value
          }
        })
    },
    // 查询发货公司
    getOutCompany() {
      let params = {
        querys: [],
        pageBean: {
          page: -1,
          pageSize: -1,
        },
      }
      params.querys.push(
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'status',
          relation: 'AND',
          value: '2',
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'matCompanyId',
          relation: 'AND',
          value: this.parameter.matCompanyId,
        }
      )
      this.$http
        .post('${portal}/arrival/v1/pageVendorGroup', params)
        .then((res) => {
          if (res.data.state) {
            this.vendorList = res.data.value.rows
          }
        })
    },
    changeContract(res) {
      this.vendorList.forEach((item) => {
        if (item.vendorId === res) {
          this.parameter.vendorId = item.vendorId
          this.parameter.vendorName = item.vendorName
          this.parameter.vendorCode = item.vendorCode
          this.parameter.isdDetail = []
        }
      })
    },
    selectOne(row) {
      reconciliationManagement.selectOne(row.id).then((res) => {
        console.log(res)
        this.parameter = res.data.value
      })
    },
    handleSelectionChange(val) {
      this.receiptList = val
    },
    getTableData() {
      this.params.querys = [
        {
          group: 'main',
          operation: 'IN',
          parentGroup: '',
          property: 'status',
          relation: 'AND',
          value: [1],
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'vendorId',
          relation: 'AND',
          value: this.parameter.vendorId,
        },
      ]
      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])
      }
      reconciliationManagement.querycCntractDetails(this.params).then((res) => {
        this.dialogTableData = res.data.value.rows
      })
    },

    handleSearch() {
      this.getTableData()
    },

    clearSearchForm() {
      this.queryParams[0].value = ''
      this.getTableData()
    },
    handleDialogTableSubmit() {
      this.parameter.receiptId = this.receiptList
        .map((item) => {
          return item.id
        })
        .join(',')
      this.parameter.receiptCode = this.receiptList
        .map((item) => {
          return item.receiptCode
        })
        .join(',')
      this.dialogVisible = false
      this.$nextTick(() => {
        this.$refs.formInfo.clearValidate('receiptId')
      })
    },
    handleDialogClose(done) {
      done()
    },
    openReceipt() {
      if (this.parameter.vendorId == '') {
        this.$message.error('请选择对账单位')
        return
      } else {
        this.dialogVisible = true
        this.getTableData()
      }
    },
    // 获取收货明细
    getLoad(data) {
      console.log(data,2222222);
      this.parameter.isdDetail = data
      this.dialogTableData.forEach(item=>{
        this.parameter.isdDetail.forEach(val=>{
          if(item.arrivalId == val.arrivalId){
            val.arrivalCode = item.arrivalCode
          }
        })
      })
      this.parameter.isdDetail.forEach((item) => {
        item.recCode = this.parameter.isdCode
        this.parameter.totalAmount += Number(item.taxInvalue)
        this.parameter.taxAmount += Number(item.taxValue)
        this.parameter.amount += Number(item.amount)
      })
      this.detailList = data
    },
    //打开收货明细弹窗
    addTable() {
      if (this.parameter.vendorId == '') {
        this.$message.error('请选择对账单位')
        return
      }
      if (this.parameter.receiptId == '') {
        this.$message.error('请选择收货单')
        return
      }
      this.$refs.detials.handleOpen(this.receiptList)
    },
    //列表删除行
    delTable(index, row) {
      this.parameter.isdDetail.splice(index, 1)
    },
    //编辑
    addModifyBtn() {
      if (this.$route.query.editRows) {
        console.log()
        this.breadcrumbOpt[1].breadcrumbName = '编辑'
        this.modifychoData(this.$route.query.editRows)
      } else {
        this.breadcrumbOpt[1].breadcrumbName = '新增'
        this.getCode()
      }
    },
    //获取修改回显数据
    modifychoData(val) {
      console.log(val)
    },
    // 关闭//面包屑点击
    handleClose() {
      if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
        this.$router.push({
          name: 'statementManagement',
          params: {
            pageBean: this.$route.query.pageBean,
          },
        })
      } else {
        this.$router.push({
          name: 'statementManagement',
        })
      }
      this.parameter = {}
    },
    // 保存
    handleSave() {
      this.parameter.isdDetail.forEach((item) => {
        delete item.id
      })
      let moment = require('moment')
      this.parameter.isdLastchgdate = moment().format('YYYY-MM-DD HH:ss:mm')
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          this.loadingBtn = true
          reconciliationManagement.batchSubmit(this.parameter).then((res) => {
            this.loadingBtn = false
            if (res.data.state) {
              this.$message.success('保存成功！')
              this.$router.go(-1)
            }
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
// /deep/.el-row {
//   padding: 0 100px;
// }
/deep/.el-row {
  display: flex;
  justify-content: center;
}
.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;
    }
  }
}
</style>
