<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="12">
            <el-form-item label="采购方" prop="matCompanyName">
              <!-- <el-input
                clearable
                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="12">
            <el-form-item label="供货方" prop="vendorName">
              <!-- <el-input
                clearable
                v-model="parameter.vendorName"
                placeholder="请输入供货方"
              ></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="12">
            <el-form-item label="不含税总金额(元)" prop="orderAmount">
              <el-input clearable v-model="parameter.orderAmount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税总金额(元)" prop="taxInvalue">
              <el-input clearable v-model="parameter.taxInvalue"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="$route.query.editRows">
          <el-col :span="12">
            <el-form-item label="订单编码" prop="orderCode">
              <el-input
                clearable
                v-model="parameter.orderCode"
                placeholder="请输入订单编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单时间" prop="orderCreatedate">
              <el-date-picker
                v-model="parameter.orderCreatedate"
                disabled
                type="date"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="编制人" prop="createName">
              <el-input
                clearable
                v-model="parameter.createName"
                placeholder="请输入编制人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同选择" prop="contractId">
              <el-select
                v-model="parameter.contractId"
                filterable
                placeholder="请选择合同"
                @change="changeContract"
              >
                <el-option
                  v-for="item in dialogTableData"
                  :key="item.id"
                  :label="item.contrName"
                  :value="item.id"
                >
                </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>
        <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" prop="matCode">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.matCode"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" prop="matName">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.matName"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" prop="matSpec">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.matSpec"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="计量单位" min-width="100" prop="matUnit">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.matUnit"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="预计数量" min-width="100" prop="matNum">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.matNum"
                @input="changeNum"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="含税单价(元)"
            min-width="120"
            prop="taxInprice"
          >
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.taxInprice"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="含税金额(元)"
            min-width="90"
            prop="taxInvalue"
          >
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.taxInvalue"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="不含税单价(元)"
            min-width="120"
            prop="orderPrice"
          >
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.orderPrice"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="不含税金额(元)"
            min-width="90"
            prop="orderAmount"
          >
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.orderAmount"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="税率(%)" min-width="80" prop="taxRate">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.taxRate"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="税额(元)" min-width="80" prop="taxValue">
            <template slot-scope="scope">
              <el-input
                clearable
                v-model="scope.row.taxValue"
                disabled
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="right"
            width="90px"
            :index="999"
          >
            <template slot="header">
              <el-button
                :disabled="!parameter.contractId"
                size="mini"
                type="warning"
                circle
                icon="el-icon-plus"
                @click="addTable"
              />
            </template>
            <template slot-scope="scope">
              <el-button
                v-if="!scope.row.id"
                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[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="contrName" label="合同名称">
          </el-table-column>
          <el-table-column
            align="center"
            prop="contractNumber"
            label="合同编号"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="treatyContents"
            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" @click="handleDialogTableSubmit">
          下一步
        </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="物料选择"
      :visible.sync="dialogVisibleDetial"
      width="70%"
      :before-close="handleDialogCloseDetial"
    >
      <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="queryParamsDetial[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="handleSearchDetial"
          >
            搜索
          </el-button>
          <el-button
            size="small"
            icon="el-icon-refresh-right"
            class="btn btn-plus"
            @click="clearSearchFormDetial"
          >
            重置
          </el-button>
        </div>
      </div>
      <div class="dialog-table">
        <el-table
          ref="dialogTableDetial"
          :data="dialogTableDataDetial"
          style="width: 100%"
        >
          <el-table-column align="center" type="selection" width="55">
          </el-table-column>

          <el-table-column align="center" prop="matMaterial" label="物料牌号">
          </el-table-column>
          <el-table-column align="center" prop="matName" label="物料名称">
          </el-table-column>

          <el-table-column align="center" prop="matSpec" label="规格型号">
          </el-table-column>
          <el-table-column align="center" prop="matUnit" label="计量单位">
          </el-table-column>
          <el-table-column align="center" prop="num" label="数量">
          </el-table-column>
          <el-table-column align="center" prop="feeMoney" label="服务费金额">
          </el-table-column>
        </el-table>
      </div>
      <div class="dialog-table-page">
        <el-pagination
          ref="paginationPanel"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageBean.page"
          :page-sizes="[20, 30, 40, 50]"
          :page-size="params.pageBean.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="params.pageBean.total"
        >
        </el-pagination>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleDetial = false"> 取 消 </el-button>
        <el-button type="primary" @click="handleDialogTableSubmitDetial">
          确 定
        </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 multipleInput from '../../../SupplierManagement/blacklistSupplier/component/multipleInput.vue'
import expertPoolUnits from './expertPoolUnits.vue'
import expertOrgUnits from './expertOrgUnits.vue'
// import {uploadMixin} from '@/mixins/uploadMixin'
export default {
  name: 'orderMangeAddDialog',
  components: {Breadcrumb, expertPoolUnits, expertOrgUnits, multipleInput},
  props: {
    editData: Object,
  },
  // mixins: [uploadMixin],
  data() {
    return {
      centralizedData: [
        {name: '是', id: 1},
        {name: '否', id: 0},
      ],
      breadcrumbOpt: [{breadcrumbName: '订单管理'}, {breadcrumbName: '新增'}],
      rules: {
        contractId: [
          {
            required: true,
            message: '请选择合同',
            trigger: 'blur',
          },
        ],
        createName: [
          {
            required: true,
            message: '请输入编制人',
            trigger: 'blur',
          },
        ],
        matCompanyName: [
          {
            required: true,
            message: '请选择采购方',
            trigger: 'blur',
          },
        ],
        vendorName: [
          {
            required: true,
            message: '请选择供货方',
            trigger: 'blur',
          },
        ],
        // orderCreatedate: [
        //   {
        //     required: true,
        //     message: '请选择订单时间',
        //     trigger: 'blur',
        //   },
        // ],
        status: [
          {
            required: true,
            message: '请选择订单状态',
            trigger: 'blur',
          },
        ],
        approvalStatus: [
          {
            required: true,
            message: '请选择审批状态',
            trigger: 'blur',
          },
        ],
      },
      parameter: {
        detailsList: [],
        orderAmount: 0,
        taxInvalue: 0,
        // status: '1',
        // approvalStatus: '1',
      },
      statusList: [
        {label: '未确认', value: '1'},
        {label: '已确认', value: '2'},
      ], // 订单状态
      approvalStatusList: [
        {label: '审批中', value: '1'},
        {label: '已审批', value: '2'},
        {label: '已撤回', value: '3'},
      ], // 审批状态
      dialogVisibleDetial: false,
      dialogVisible: false,
      dialogTableDataDetial: [],
      dialogTableData: [],
      params: {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
      },
      queryParamsDetial: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'matName',
          relation: 'AND',
          value: '',
        },
      ],
      queryParams: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'contrName',
          relation: 'AND',
          value: '',
        },
      ],
      enterpriseList: [],
      supplierList: [],
      selectObj: {},
    }
  },
  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.parameter.createName = username
    this.parameter.createBy = userId
    // this.getDate()
    this.getTableData()
  },
  mounted() {},
  methods: {
    changeContract(res) {
      console.log(res, 'res')
      this.dialogTableData.forEach((item) => {
        if (item.id === res) {
          this.parameter.contractName = item.contrName
          this.parameter.contractNumber = item.contrCode
          this.parameter.detailsList = []
        }
      })
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.dialogTable.clearSelection()
        this.$refs.dialogTable.toggleRowSelection(val[val.length - 1])
      }
      this.selectObj = val[val.length - 1]
      if (!this.selectObj) {
        this.selectObj = {}
      }
    },

    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.sorter[0].direction) {
      //     this.params.sorter.push(this.sorter[0])
      // }

      purchaseOrder.querycCntract(this.params).then((res) => {
        this.dialogTableData = res.data.value.rows
      })
    },
    getTableDataDetial() {
      this.params.querys = [
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'contractId',
          relation: 'AND',
          value: this.parameter.contractId,
        },
      ]
      this.params.sorter = []
      if (this.queryParamsDetial[0].value) {
        this.params.querys.push(this.queryParamsDetial[0])
      }

      // if (this.sorter[0].direction) {
      //     this.params.sorter.push(this.sorter[0])
      // }
      purchaseOrder.querycCntractDetails(this.params).then((res) => {
        this.dialogTableDataDetial = res.data.value.rows
        this.params.pageBean = {
          page: res.data.value.page,
          pageSize: res.data.value.pageSize,
          total: res.data.value.total,
        }
      })
    },
    handleCurrentChange(page) {
      this.params.pageBean = {...this.params.pageBean, page}
      this.getTableDataDetial()
    },
    handleSizeChange(pageSize) {
      this.params.pageBean = {...this.params.pageBean, pageSize}
      this.getTableDataDetial()
    },
    handleSearch() {
      this.getTableData()
    },

    handleSearchDetial() {
      this.getTableDataDetial()
    },
    clearSearchFormDetial() {
      this.queryParamsDetial[0].value = ''
      this.getTableDataDetial()
    },
    clearSearchForm() {
      this.queryParams[0].value = ''
      this.getTableData()
    },
    handleDialogTableSubmit() {
      let selection = this.selectObj

      this.getTableDataDetial(selection)
      this.dialogVisible = false
      this.dialogVisibleDetial = true
    },
    handleDialogTableSubmitDetial() {
      this.parameter.detailsList = []
      let selection = this.$refs.dialogTableDetial.selection
      this.parameter.detailsList.push(...selection)
      this.parameter.detailsList.forEach((item) => {
        item.matNum = item.num
        if (item.taxInprice && item.taxValue) {
          item.orderPrice = item.taxInprice - item.taxValue
          item.orderAmount = item.orderPrice * item.num
        } else {
          item.orderPrice = 0
          item.orderAmount = 0
        }
      })
      this.dialogVisibleDetial = false
    },
    //列表添加选择合同信息
    addTable() {
      this.getTableDataDetial()
      this.dialogVisibleDetial = true
    },
    //列表删除行
    delTable(index, row) {
      this.parameter.detailsList.splice(index, 1)
      if (row.id) {
        this.parameter.deleteDetailsId.push(row.id)
      }
    },
    //编辑
    addModifyBtn() {
      if (this.$route.query.editRows) {
        this.breadcrumbOpt[1].breadcrumbName = '编辑'
        this.modifychoData(this.$route.query.editRows)
      } else {
        this.breadcrumbOpt[1].breadcrumbName = '新增'
      }
    },
    //获取修改回显数据
    modifychoData(val) {
      console.log(val)
    },
    // 关闭//面包屑点击
    handleClose() {
      if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
        this.$router.push({
          name: 'orderMange',
          params: {
            pageBean: this.$route.query.pageBean,
          },
        })
      } else {
        this.$router.push({
          name: 'orderMange',
        })
      }

      // this.$emit('closeComponent')
      this.parameter = {}
      // this.$refs.formInfo.clearValidate()
    },
    // 保存
    handleSave() {
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          if (!this.$route.query.editRows && this.parameter.detailsList) {
            this.parameter.detailsList.forEach((item) => {
              delete item['id']
            })
          }
          purchaseOrder.batchSubmit(this.parameter).then((res) => {
            if (res.data.state) {
              this.$message.success('保存成功！')
              this.$router.go(-1)
            } else {
              this.$message.success('保存失败！')
            }
          })
        }
      })
    },

    handleDialogClose(done) {
      done()
    },
    handleDialogCloseDetial(done) {
      done()
    },
    open(type) {
      this.$refs[type].add()
    },
    deleteTags(index, key) {
      if (!index) {
        this[key] = []
      } else {
        this[key].splice(index, 1)
      }
      if (key === 'enterpriseList') {
        this.$set(this.parameter, 'matCompanyName', '')
        this.$set(this.parameter, 'matCompanyId', '')
        this.$set(this.parameter, 'matCompanyCode', '')
      } else {
        this.$set(this.parameter, 'vendorName', '')
        this.$set(this.parameter, 'vendorId', '')
        this.$set(this.parameter, 'vendorCode', '')
      }
    },
    addDetail(list, key) {
      this[key] = list
      if (key === 'enterpriseList') {
        this.$set(this.parameter, 'matCompanyName', list[0].name)
        this.$set(this.parameter, 'matCompanyId', list[0].id)
        this.$set(this.parameter, 'matCompanyCode', list[0].code)
      } else {
        this.$set(this.parameter, 'vendorName', list[0].name)
        this.$set(this.parameter, 'vendorId', list[0].id)
        this.$set(this.parameter, 'vendorCode', list[0].code)
      }
    },

    changeNum(data) {
      let taxsum = 0
      let ordersum = 0
      this.parameter.detailsList.forEach((item) => {
        if (item.matNum != null && item.taxInprice != null) {
          item.taxInvalue = item.matNum * item.taxInprice
        }
        if (item.matNum != null && item.orderPrice != null) {
          item.orderAmount = item.matNum * item.orderPrice
        }
      })
      this.parameter.detailsList.forEach((item) => {
        if (item.taxInvalue != null) {
          taxsum = taxsum + item.taxInvalue
        }
        if (item.orderAmount != null) {
          ordersum = ordersum + item.orderAmount
        }
      })
      this.$set(this.parameter, 'orderAmount', taxsum)
      this.$set(this.parameter, 'taxInvalue', ordersum)
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body {
    padding-top: 10px;
    background-color: #f5f5f5;
}
/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-single  {
    /deep/ thead {
      .el-table-column--selection {
        .cell {
          display: none;
        }
      }
    }
  }
.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>
