<template>
  <div class="bg-in-stock">
    <el-form ref="purchaseContractForm" :model="purchaseContractForm" label-width="120px" inline style="width:1300px">
      <h3>采购合同</h3>
      <el-form-item label="签订时间" prop="sign_time">
        <el-date-picker v-model="purchaseContractForm.sign_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="supplier_id">
        <el-button :disabled="type === 'detail'" class="button" size="mini" type="primary"
          @click="handleSelectSupplier">选择</el-button>
        <span v-if="purchaseContractForm.supplier_name">{{ purchaseContractForm.supplier_name }}</span>
      </el-form-item>
      <el-form-item label="制单人" prop="creator_id">
        <el-select v-model="purchaseContractForm.creator_id" :disabled="type === 'detail'">
          <el-option v-for="item in adminList" :key="item.id" :label="item.real_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="制单时间" prop="creator_time">
        <el-date-picker v-model="purchaseContractForm.creator_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail'" placeholder="选择日期时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="附件" prop="contract_annex">
        <el-upload v-if="type !== 'detail'" multiple :action="MixinUploadApi" :file-list="fileList"
          :on-success="(res) => { purchaseContractForm.contract_annex = res.url }" :limit="1"
          :disabled="type === 'detail'">
          <el-button size="mini" type="primary" :disabled="type === 'detail'">上传</el-button>
        </el-upload>
        <a
          v-if="purchaseContractForm.contract_annex && type !== 'add'"
          :href="purchaseContractForm.contract_annex"
          target="_blank"

          style="color:#409EFF;font-size:12px">下载附件</a>
      </el-form-item>
      <el-form-item label="采购计划">
        <el-button v-if="type !== 'detail'" class="button" size="mini" type="primary" :disabled="type === 'detail'"
          @click="handleSelectPlan">选择</el-button>
        <span v-if="purchaseContractForm.plan_sn">{{ purchaseContractForm.plan_sn }}</span>
      </el-form-item>
      <el-form-item label="说明" prop="contract desc" style="white-space: nowrap;">
        <el-input style="width:525px" v-model="purchaseContractForm.contract_desc" type="textarea"
          :disabled="type === 'detail'" :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入说明"></el-input>
      </el-form-item>
      <div class="mx">
        <h3>合同明细</h3>
        <el-button class="button" size="mini" type="primary" v-if="type !== 'detail'"
          @click="handleSelectGoods">选择</el-button>
      </div>
      <div style="display:block">
        <el-form-item>
          <el-table :data="purchaseContractForm.product_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="商品编号" width="150">
              <template slot-scope="scope">
                {{ scope.row.product_sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称" width="150">
              <template slot-scope="scope">
                {{ scope.row.product_name }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号" width="150">
              <template slot-scope="scope">
                {{ scope.row.specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位" width="50">
              <template slot-scope="scope">
                {{ scope.row.unit }}
              </template>
            </el-table-column>
            <el-table-column label="单价" width="150">
              <template slot-scope="scope">
                <el-input :maxlength="12" v-model="scope.row.price" @input="jisuan(scope.row)"
                  :disabled="type === 'detail'">
                  <template slot="prepend">¥</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150">
              <template slot-scope="scope">
                <el-input :maxlength="12" v-model="scope.row.num" @input="jisuan(scope.row)"
                  :disabled="type === 'detail'" />
              </template>
            </el-table-column>
            <el-table-column label="税率(%)" width="80">
              <template slot-scope="scope">
                <el-input :maxlength="12" v-model="scope.row.tax_rate" :disabled="type === 'detail'" />
              </template>
            </el-table-column>
            <el-table-column label="合价" width="150">
              <template slot-scope="scope">
                {{ scope.row.total_price }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" v-if="type !== 'detail'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                  @click="purchaseContractForm.product_list.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
      <div class="mx" v-if="type === 'detail'">
        <h3>入库单列表</h3>
      </div>
      <div v-if="type === 'detail'">
        <el-form-item>
          <en-table-layout :tableData="rktableData.data" style="width:1100px;padding:0px;" :toolbar="false" border>
            <template slot="table-columns">
              <el-table-column prop="sn" label="入库单编号">
                <template slot-scope="scope">
                  <router-link v-if="checkPermission(['purchaseWarehousing'])" style="color: #409eff;"
                    :to="{ name: 'purchaseWarehousingDetail', params: { id: scope.row.id } }">{{ scope.row.sn
                    }}</router-link>
                  <span v-else>{{scope.row.sn}}</span>
                </template>
              </el-table-column>
              <el-table-column label="入库日期">
                <template slot-scope="scope">{{ scope.row.entry_time | unixToDate }}</template>
              </el-table-column>
              <el-table-column prop="dept_name" label="所属部门" />
              <el-table-column prop="warehouse_name" label="仓库" />
              <el-table-column prop="supplier_name" label="供应商" />
              <el-table-column prop="plate_number" label="车牌号" />
              <el-table-column prop="handled_by_name" label="经手人" />
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
              </el-table-column>
              <el-table-column prop="audit_by" label="审核人" />
            </template>

            <el-pagination v-if="rktableData" slot="pagination" @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange" :current-page="rktableData.page_no"
              :page-sizes="[10, 20, 50, 100]" :page-size="rktableData.page_size"
              layout="total, sizes, prev, pager, next, jumper" :total="rktableData.data_total">
            </el-pagination>
          </en-table-layout>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button type="primary" @click="submitpurchaseContractForm" v-if="type !== 'detail'">保存
      </el-button>
      <el-button @click="roBack()">返回
      </el-button>
    </div>
  </div>
</template>

<script>
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Purchase from '@/api/purchase'
import * as API_Auth from '@/api/auth'
import { Foundation } from '~/ui-utils'
import { mapGetters } from 'vuex'
export default {
  name: 'purchaseContractAdd',
  data() {
    return {
      rktableData: '',
      params: {
        page_no: 1,
        page_size: 10
      },
      adminList: [],
      fileList: [],
      supplierList: [],
      deptList: [],
      id: '',
      type: '',
      /** 商品列表 */
      goodsList: [],

      /** 出库单表单*/
      purchaseContractForm: {
        plan_sn: '',
        creator_id: '',
        product_list: []
      }
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === 'purchaseContractAdd') {
          this.purchaseContractForm.creator_id = this.user.uid
          this.$set(this.purchaseContractForm, 'creator', this.user.username)
          this.$set(this.purchaseContractForm, 'sign_time', new Date().getTime())
          this.$set(this.purchaseContractForm, 'creator_time', new Date().getTime())
          this.type = 'add'
        } else if (this.$route.name === 'purchaseContractDetail') {
          this.type = 'detail'
        }
        if (this.$route.params.id) {
          this.id = this.$route.params.id
          this.GET_ContractDetail()
        }
      }
    }
  },
  mounted() {
    this.GET_DeptList()
    this.GET_SupplierList()
    this.GET_AdministratorList()
  },
  computed: {
    ...mapGetters(['user'])
  },
  methods: {
    // 选择采购计划
    async handleSelectPlan() {
      const Plan = await this.$EnPickerPlan({
        goodsApi: '/admin/procurement/plan',
        limit: 1,
        selectedIds: this.purchaseContractForm.purchase_plan_id && [this.purchaseContractForm.purchase_plan_id]
      })
      if (!Plan.length) return
      this.purchaseContractForm.plan_sn = Plan[0].sn
      this.purchaseContractForm.plan_id = Plan[0].id
      API_Purchase.getPurchaseProductList(Plan[0].id).then(response => {
        const product_list = []
        response.forEach(item => {
          const haveSamePlan = this.purchaseContractForm.product_list.some(v => {
            return v.plan_id === item.plan_id
          })
          if (!haveSamePlan) {
            item.product_sn = item.product_sn
            item.product_name = item.product_name
            item.specification = item.specification
            item.product_id = item.product_id
            item.category_name = item.category_name
            item.category_id = item.category_id
            item.unit = item.unit
            item.total_price = 0
            item.plan_id = item.plan_id
            product_list.push(item)
          }
        })
        if (product_list.length) {
          if (this.purchaseContractForm.product_list && this.purchaseContractForm.product_list.length) {
            this.purchaseContractForm.product_list = this.purchaseContractForm.product_list.concat(product_list)
          } else {
            this.purchaseContractForm.product_list = product_list
          }
        }
      })
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    /** 获取采购入库列表 */
    GET_PurchaseWarehousingList() {
      API_Purchase.getPurchaseWarehousingList(this.params).then(response => {
        this.rktableData = response
      })
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size
      this.GET_PurchaseWarehousingList()
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page
      this.GET_PurchaseWarehousingList()
    },

    /** 入库单状态 */
    statusFilter(val) {
      switch (val) {
        case 'NotSubmit':
          return '未提交'
        case 'Submit':
          return '已提交'
        case 'AuditPass':
          return '审核通过'
        case 'AuditReject ':
          return '审核驳回'
        default:
          return ''
      }
    },
    // 选择供应商
    async handleSelectSupplier() {
      const Supplier = await this.$EnPickerSupplier({
        goodsApi: '/admin/erp/supplier',
        limit: 1,
        selectedIds: this.purchaseContractForm.supplier_id && [this.purchaseContractForm.supplier_id]
      })
      if (!Supplier.length) return
      this.$set(this.purchaseContractForm, 'supplier_id', Supplier[0].id)
      this.$set(this.purchaseContractForm, 'supplier_name', Supplier[0].custom_name)
    },
    jisuan(row) {
      if (row.price && row.num) {
        row.total_price = row.price * row.num
      }
    },
    roBack() {
      const { callback } = this.$route.params
      if (typeof callback === 'function') callback()
      this.$store.dispatch('delCurrentViews', {
        view: this.$route,
        $router: this.$router
      })
      this.$router.push({ name: 'purchaseContract' })
    },
    submitpurchaseContractForm() {
      const { id } = this.purchaseContractForm
      const params = this.MixinClone(this.purchaseContractForm)
      // if (params.supplier_id) {
      //   params.supplier_name = this.supplierList.find(dept => dept.id === params.supplier_id).custom_name
      // }
      params.sign_time = Math.floor(params.sign_time / 1000)
      params.creator_time = Math.floor(params.creator_time / 1000)
      if (id) {
        API_Purchase.editContract(id, params).then(response => {
          this.$message.success('修改成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'purchaseContract' })
        })
      } else {
        API_Purchase.addContract(params).then(() => {
          this.$message.success('添加成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'purchaseContract' })
        })
      }
    },
    /** 获取供应商 */
    GET_SupplierList() {
      API_BasicSetting.getSupplierListAll().then(response => {
        this.supplierList = response
      })
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    // 选择商品
    async handleSelectGoods() {
      const Goods = await this.$EnPickerGoods({
        goodsApi: '/admin/erp/product',
        selectedIds: this.id ? this.purchaseContractForm.product_list && this.purchaseContractForm.product_list.map(item => item.product_id) : this.purchaseContractForm.product_list.map(item => item.product_id)
      })
      if (!Goods.length) return
      const product_list = Goods.map(item => {
        item.product_sn = item.sn
        item.product_name = item.name
        item.specification = item.specification
        item.product_id = item.id
        item.category_name = item.category_name
        item.category_id = item.category_id
        item.unit = item.unit
        item.total_price = 0
        return item
      })
      this.purchaseContractForm.product_list = this.purchaseContractForm.product_list && this.purchaseContractForm.product_list.length ? this.purchaseContractForm.product_list.concat(product_list) : this.purchaseContractForm.product_list = product_list
    },
    /** 获取采购计划详情页面数据 */
    GET_ContractDetail() {
      API_Purchase.getContractInfo(this.id).then(response => {
        this.purchaseContractForm = response
        this.purchaseContractForm.sign_time = Math.floor(this.purchaseContractForm.sign_time * 1000)
        this.purchaseContractForm.creator_time = Math.floor(this.purchaseContractForm.creator_time * 1000)
        this.fileList = response.contract_annex ? [{ name: '附件', url: response.contract_annex }] : []
        this.params.contract_id = this.id
        this.GET_PurchaseWarehousingList()
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;

  .button {
    margin-left: 10px;
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}

/deep/ .el-form-item {
  width: 400px;
  white-space: nowrap;
}
</style>
