<template>
  <div class="bg-in-stock">
    <el-form ref="purchasePlanForm" :model="purchasePlanForm" label-width="120px" inline style="width:1300px">
      <h3>采购计划</h3>
      <el-form-item label="编制时间" prop="formation_time">
        <el-date-picker v-model="purchasePlanForm.formation_time" value-format="timestamp" type="datetime"
          :disabled="type === 'detail'" placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属部门" prop="dept_id">
        <el-cascader v-model="purchasePlanForm.dept_id" :options="deptList" :disabled="type === 'detail'" :props="{
          label: 'name',
          value: 'id',
          emitPath: false,
          checkStrictly: true
        }" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="计划供应时间" prop="supplier_time">
        <el-date-picker value-format="timestamp" v-model="purchasePlanForm.supplier_time" type="datetime"
          :disabled="type === 'detail'" placeholder="选择日期时间" style="width:160px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="supplier_id">
        <el-button v-if="purchasePlanForm.supplier_name" class="button" size="mini" type="text"
          @click="handleSelectSupplier">{{
            purchasePlanForm.supplier_name
          }}</el-button>
        <el-button v-else :disabled="type === 'detail'" class="button" size="mini" type="primary"
          @click="handleSelectSupplier">选择</el-button>
      </el-form-item>
      <el-form-item label="编制人" prop="formation_person_id">
        <!-- <el-input v-model="purchasePlanForm.formation_person" :minlength="2" :maxlength="20" clearable :disabled="true"
          placeholder="请输入编制人"></el-input> -->
        <el-select v-model="purchasePlanForm.formation_person_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></el-form-item>
      <el-form-item label="采购说明" prop="procurement_desc" style="width:800px">
        <el-input style="width:525px" v-model="purchasePlanForm.procurement_desc" :maxlength="120" type="textarea"
          :disabled="type === 'detail'" :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入采购说明 最大120字"></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="purchasePlanForm.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="150">
              <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.procurement_num" onkeyup="value=value.replace(/[^\d]/g,'')"
                  :disabled="type === 'detail'" />
              </template>
            </el-table-column>
            <el-table-column label="备注" width="150">
              <template slot-scope="scope">
                <el-input :maxlength="99" v-model="scope.row.remark" :disabled="type === 'detail'" />
              </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="purchasePlanForm.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 v-if="type !== 'detail'" type="primary" @click="submitpurchasePlanForm">保存
      </el-button>
      <el-button @click="roBack()">返回
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as API_Purchase from '@/api/purchase'
import { Foundation } from '~/ui-utils'
import * as API_Setting from '@/api/setting'
import * as API_Auth from '@/api/auth'
export default {
  name: 'purchasePlanAdd',
  data() {
    return {
      adminList: [],
      deptList: [],
      deptListAll: [],
      rktableData: '',
      params: {
        page_no: 1,
        page_size: 10
      },
      id: '',
      type: '',
      /** 出库单表单*/
      purchasePlanForm: {
        formation_person_id: '',
        product_list: []
      }
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === 'purchasePlanAdd') {
          this.purchasePlanForm = {
            formation_person_id: '',
            product_list: []
          }
          this.purchasePlanForm.formation_person_id = this.user.uid
          this.purchasePlanForm.dept_id = this.user.dept_id
          this.purchasePlanForm.formation_person = this.user.username
          this.$set(this.purchasePlanForm, 'formation_time', new Date().getTime())
        } else if (this.$route.name === 'purchasePlanDetail') {
          this.type = 'detail'
        }
        if (this.$route.params.id) {
          this.id = this.$route.params.id
          this.GET_PurchasePlanDetail()
        }
        this.GET_AdministratorList()
      }
    }
  },
  mounted() {
    this.GET_DeptList()
  },
  methods: {
    // 选择供应商
    async handleSelectSupplier() {
      const Supplier = await this.$EnPickerSupplier({
        goodsApi: '/admin/erp/supplier',
        limit: 1,
        selectedIds: this.purchasePlanForm.supplier_id && [this.purchasePlanForm.supplier_id]
      })
      if (!Supplier.length) return
      this.$set(this.purchasePlanForm, 'supplier_id', Supplier[0].id)
      this.$set(this.purchasePlanForm, 'supplier_name', Supplier[0].custom_name)
    },
    /** 获取人员列表 */
    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 ''
      }
    },
    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: 'purchasePlan' })
    },
    submitpurchasePlanForm() {
      const { id } = this.purchasePlanForm
      const params = this.MixinClone(this.purchasePlanForm)
      if (!params.dept_id) {
        this.$message.error('请选择部门！')
        return
      }
      if (!params.product_list.length) {
        this.$message.error('请选择采购明细！')
        return
      }
      params.dept_name = this.deptListAll.find(dept => dept.id === params.dept_id).name
      params.formation_time = Math.floor(params.formation_time / 1000)
      params.supply_time = Math.floor(params.supply_time / 1000)
      if (params.formation_person_id) {
        params.formation_person = this.adminList.find(admin => admin.id === params.formation_person_id).real_name
      }
      if (params.product_list && params.product_list.length) {
        params.product_list.forEach(function(i) {
          i.supply_time = Math.floor(i.supply_time / 1000)
        })
      }
      if (id) {
        API_Purchase.editPurchasePlan(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: 'purchasePlan' })
        })
      } else {
        API_Purchase.addPurchasePlan(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: 'purchasePlan' })
        })
      }
    },
    // 选择商品
    async handleSelectGoods() {
      const Goods = await this.$EnPickerGoods({
        goodsApi: '/admin/erp/product',
        selectedIds: this.id ? this.purchasePlanForm.product_list && this.purchasePlanForm.product_list.map(item => item.product_id) : this.purchasePlanForm.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
        return item
      })
      this.purchasePlanForm.product_list = this.purchasePlanForm.product_list && this.purchasePlanForm.product_list.length ? this.purchasePlanForm.product_list.concat(product_list) : this.purchasePlanForm.product_list = product_list
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
        this.deptListAll = response
      })
    },
    /** 获取采购计划详情页面数据 */
    GET_PurchasePlanDetail() {
      API_Purchase.getPurchasePlanInfo(this.id).then(response => {
        this.purchasePlanForm = response
        this.purchasePlanForm.formation_time = Math.floor(this.purchasePlanForm.formation_time * 1000)
        this.purchasePlanForm.supply_time = Math.floor(this.purchasePlanForm.supply_time * 1000)
        if (this.purchasePlanForm.product_list && this.purchasePlanForm.product_list.length) {
          this.purchasePlanForm.product_list.forEach(function(i) {
            i.supply_time = Math.floor(i.supply_time * 1000)
          })
        }
        this.params.purchase_plan_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;
}
</style>
