<template>
  <div class="purchase_order">
    <Toptitle title="采购订单">
      <slot name="titleButton">
        <!-- <Button type="primary"
                @click="handleGoPage(1,'')"
                style="margin-right:10px;">新增</Button> -->
        <!-- <Button @click="handleCodeRule"
                type="primary"
                ghost
                style="margin-right:10px;">编码规则</Button> -->
      </slot>
    </Toptitle>
    <div class="content">
    <div class="purchase_order_search">
      <Form :label-width="100"
            :model="searchData">
        <FormItem label="订单号:" style="width:300px">
          <Input type="text"
                 size="small"
                 v-model="searchData.order_no"
                 style="width: 150px"
                 clearable
                 placeholder="订单号" />
        </FormItem>
         <FormItem label="采购订单类型:" style="width:300px">
          <Select v-model="searchData.type_id"
                  size="small"
                  clearable
                  filterable
                  label-in-value
                  style="width: 150px">
            <Option v-for="(sitem) in purchaseTypeList"
                    :key="sitem.id"
                    :label="sitem.title"
                    :value="sitem.id">
            </Option>
          </Select>
        </FormItem>
        <FormItem label="供应商名称:" style="width:300px">
          <Input type="text"
                 size="small"
                 v-model="searchData.supply_title"
                 style="width: 150px"
                 clearable
                 placeholder="供应商名称" />
        </FormItem>
        <FormItem label="订单状态:" style="width:300px">
          <Select v-model="searchData.lock"
                  size="small"
                  clearable
                  style="width: 150px">
            <Option label='已关闭'
                    :value='0' />
            <Option label='部分关闭'
                    :value='1' />
                    <Option label='正常'
                    :value='2' />
          </Select>
        </FormItem>
        <FormItem label="制单人:" style="width:300px">
          <Select v-model="searchData.crt_id"
                  size="small"
                  clearable
                  style="width: 150px">
            <Option v-for="(sitem) in userList"
                    :key="sitem.id"
                    :label="sitem.nickname"
                    :value="sitem.id">
            </Option>
          </Select>
        </FormItem>
       
        <FormItem label="审批状态:" style="width:300px">
          <Select v-model="searchData.state"
                  size="small"
                  clearable
                  style="width: 150px">
            <Option label='未审核'
                    :value='0' />
            <Option label='已审核'
                    :value='1' />
          </Select>
        </FormItem>
        <FormItem label="审批人:" style="width:300px">
          <Select v-model="searchData.check_id"
                  size="small"
                  clearable
                  style="width: 150px">
            <Option v-for="(sitem) in userList"
                    :key="sitem.id"
                    :label="sitem.nickname"
                    :value="sitem.id">
            </Option>
          </Select>
        </FormItem>
        <FormItem label="预计到货日期:" style="width:450px">
          <DatePicker type="date"
                      size="small"
                      style="width: 150px"
                      placeholder="年/月/日"
                      v-model="searchData.arrive_start_time"></DatePicker>
       
       ~
          <DatePicker type="date"
                      size="small"
                      style="width: 150px"
                      placeholder="年/月/日"
                      v-model="searchData.arrive_end_time"></DatePicker>
        </FormItem>
         <FormItem label="单据日期:" style="width:450px">
          <DatePicker type="date"
                      size="small"
                      style="width: 150px"
                      placeholder="年/月/日"
                      v-model="searchData.order_start_time"></DatePicker>
       
       ~
          <DatePicker type="date"
                      size="small"
                      style="width: 150px"
                      placeholder="年/月/日"
                      v-model="searchData.order_end_time"></DatePicker>
        </FormItem>
         <FormItem label="订单创建时间:" style="width:450px">
          <DatePicker type="date"
                      size="small"
                      style="width: 150px"
                      placeholder="年/月/日"
                      v-model="searchData.start_time"></DatePicker>
       
       ~
          <DatePicker type="date"
                      size="small"
                      style="width: 150px"
                      placeholder="年/月/日"
                      v-model="searchData.end_time"></DatePicker>
        </FormItem>
        <FormItem>
          <Button type="primary"
                
                  @click="initData(searchData)"
                  style="margin-right:10px;">搜索</Button>
                    <Button type="primary"
                @click="handleGoPage(1,'')"
                style="margin-right:10px;">新增</Button>
        </FormItem>
      </Form>
    </div>
    <div class="purchase_order_content">
      <div class="purchase_order_content_table">
        <Table :columns="tableColumns"
               border
               :max-height="500"
               :data="historyTableData">
          <template slot="setSlot"
                    slot-scope="{row,index}">
                <a style="margin:0 5px"
               @click="handleSet(6,row,index)">复制</a>
            <a style="margin:0 5px"
               @click="handleSet(2,row,index)">详情</a>
            <a style="margin:0 5px"
               v-if="!row.state==1||!row.state==2"
               @click="handleSet(3,row,index)">编辑</a>
            <a style="margin:0 5px"
               v-if="!row.state==1||!row.state==2"
               @click="handleSet(4,row,index)">删除</a>
          <a style="margin:0 5px"
               @click="handleSet(5,row,index)">{{row.state==0?'审批':'弃审'}}</a>
          </template>
        </Table>
      </div>
    </div>
    </div>
    <div class="purchase_order_content_page">
          <Page :page-size-opts="[10, 20, 30, 40,100]"
                @on-page-size-change='changeSize'
                @on-change='changePage'
                :current='pageIndex'
                show-total
                :total="total"
                show-sizer
                :page-size='pageSize' />
        </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: 'PurchasingOrderList',
  components: {

  },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data () {
    // 这里存放数据
    return {
      searchData: {
        order_no: '',
        project_title: '',
        supply_title: '',
        type_id: '',
        user_id: '',
        lock: '',
        state: '',
        start_time: '',
        end_time: '',
         arrive_start_time:'',
        arrive_end_time:'',
          order_start_time:'',
        order_end_time:'',
       
      },
      purchaseTypeList: [],
      tableColumns: [
        { title: '订单号', key: 'order_no', align: 'center', minWidth: 140 },
        { title: '采购订单类型', key: 'basics_purchase_title', align: 'center', minWidth: 140 },
        { title: '供应商名称', key: 'supply_title', align: 'center', minWidth: 140 },
        {
          title: '订单状态', key: 'lock', align: 'center', minWidth: 120,
        render: (h, params) => {
            const { row } = params
            const text = row.lock == 0 ? '已关闭' :row.lock == 1?'部分关闭':'正常'
            return h('span', {}, text)
          }
        },
        { title: '制单人', key: 'user_name', align: 'center', minWidth: 100 },
        {
          title: '审批状态', key: 'state', align: 'center', minWidth: 140,
        render: (h, params) => {
            const { row } = params
            const text = row.state == 0 ? '未审批' : '已审批'
            return h('span', {}, text)
          }
        },
         { title: '审批人', key: 'check_name', align: 'center', minWidth: 100 },
        {
          title: '预计到货日期', key: 'arrive_time', align: 'center', minWidth: 140,
          render: (h, params) => {
            const { row } = params
            return h('span', {}, this.func.replaceDateNoHMS(row.arrive_time))
          }
        },
        {
          title: '单据日期', key: 'order_time', align: 'center', minWidth: 140,
          render: (h, params) => {
            const { row } = params
            return h('span', {}, this.func.replaceDate(row.order_time).split(' ')[0]||'')
          }
        },
         {
          title: '订单创建时间', key: 'crt_time', align: 'center', minWidth: 170,
          render: (h, params) => {
            const { row } = params
            return h('span', {}, this.func.replaceDate(row.crt_time))
          }
        },
        { title: '操作', key: 'code', align: 'center', minWidth: 250, slot: 'setSlot' },
      ],
      tableData: [{}],
      historyTableData:[],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      userList: [],
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 获取采购类型
    this.axios({ method: 'get', url: '/api/basic_purchase_list',params:{type_id:2} }).then((res) => { this.purchaseTypeList = res.data.data }).catch((err) => { });
    // 获取操作员
    this.axios('/api/user').then(res => this.userList = res.data.data)
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.initData()
  },
  beforeRouteLeave (to, from, next) {
    console.log(to.path != '/cms/PurchasingManage/PurchasingOrder/edit');
    if (to.path != '/cms/PurchasingManage/PurchasingOrder/edit') {
      this.$destroy()
    }
    next();
  },
  beforeRouteEnter(to,from,next){
          next(vm =>{
          if(from.name === 'PurchasingOrderEdit'){
            vm.initData()
          }
          })
  },
  methods: {
    initData () {
      let obj = JSON.parse(JSON.stringify(this.searchData))
      obj.start_time = parseInt(new Date(obj.start_time).getTime() / 1000) || ''
      obj.end_time = parseInt(new Date(obj.end_time).getTime() / 1000) || ''
      obj.order_start_time = parseInt(new Date(obj.order_start_time).getTime() / 1000) || ''
      obj.order_end_time = parseInt(new Date(obj.order_end_time).getTime() / 1000) || ''
       obj.arrive_start_time = parseInt(new Date(obj.arrive_start_time).getTime() / 1000) || ''
      obj.arrive_end_time = parseInt(new Date(obj.arrive_end_time).getTime() / 1000) || ''
      this.axios({
        method: 'get',
        url: '/api/purchase_list',
        params: {
          ...obj,
        }
      }).then((res) => {
        this.tableData = res.data.data
        this.historyTableData = this.tableData.slice(0,this.pageSize)
        this.total = res.data.total
      }).catch((err) => { });
    },
    handleSet (type, row, index) {
      // 1新增 2详情 3编辑 4删除 5提交
      switch (type) {
        case 1:
        case 2:
          case 6:
        case 3:
          this.handleGoPage(type, row.order_no)
          break;
        case 4:
          this.$Modal.confirm({
            title: '确认删除？',
            content: '此操作无法恢复，请确认！',
            onOk: () => {
              this.axios({
                method: 'post',
                url: '/api/purchase_del',
                data: {
                  order_no: row.order_no
                }
              }).then((res) => {
                this.$Message.success(res.msg)
                this.initData()
              }).catch((err) => { });
            },
            onCancel: () => { }
          })
          break;
        case 5:
          this.$Modal.confirm({
            title: '确认审核？',
            // content: '此操作无法恢复，请确认！',
            onOk: () => {
              this.axios({
                method: 'get',
                url: '/api/purchase_check',
                params: {
                  order_no: row.order_no,
                  // lock: row.lock,
                  state: row.state==0?1:0,
                }
              }).then((res) => {
                this.$Message.success(res.msg)
                this.initData()
              }).catch((err) => { });
            },
            onCancel: () => { }
          })
          break;
      }
    },
    handleGoPage (type, order_no) {
      this.$router.push({
        path: '/cms/PurchasingManage/PurchasingOrder/edit',
        query: {
          type,
          order_no,
         
        }
      })
    },
    changeSize (e) {
      this.pageSize = e;
      this.initData()
    },
    changePage (index) {
      this.pageIndex = index;
      let _start = (index - 1)*this.pageSize;
      let _end = index * this.pageSize;
      // this.initData()
      this.historyTableData = this.tableData.slice(_start,_end)
    }
  },
  // 监听属性 类似于data概念
  computed: {

  },
  // 监控data中的数据变化
  watch: {},
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
.purchase_order_search {
  padding-top: 20px;
  /deep/.ivu-form {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  /deep/.ivu-form-item {
    display: inline-block;
    width: 250px;
  }
}
.purchase_order_content {
  border-top: 1px solid #f4f4f4;
  margin-top: 20px;
  .purchase_order_content_btn {
    display: flex;
    justify-content: flex-end;
    padding: 20px 0;
  }
 
}
 .purchase_order_content_page {
    display: flex;
    justify-content: center;
    padding-top: 20px;
  }
.content{
  overflow: auto;
  height: 650px;
}
</style>
