<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="search.keyWord" placeholder="关键字" @keyup.enter.native="searchData" style="width: 200px;" class="filter-item" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        v-if="webType && isChoose == false"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreateAdd">
        增加外加工档案
      </el-button>
    </div>
    <el-table
      :data="tableData"
      size="mini"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all>
      <el-table-column
        type="index">
      </el-table-column>
      <el-table-column
        width="100"
        prop="outAssistName"
        label="加工厂类型">
        <template slot-scope="{row}">
          <b v-if="row.assistType==0">印刷</b>
          <b v-if="row.assistType==1">后工</b>
        </template>
      </el-table-column>
      <el-table-column
        width="90"
        label="状态"
        prop="outAssistName"
      >
        <template slot-scope="{row}">
          <b v-if="row.enable==0">禁用中</b>
          <b style="color: #67C23A" v-if="row.enable==1">启用中</b>
        </template>
      </el-table-column>
      <el-table-column
        width="120"
        show-overflow-tooltip
        label="外协厂名称"
        prop="outAssistName"
      >
      </el-table-column>
     <el-table-column
        width="90"
        label="加工类型"
        prop="workType"
      >
      </el-table-column>
      <el-table-column
        width="90"
        prop="workQuality"
        label="加工厂等级">
      </el-table-column>
      <el-table-column
        width="90"
        prop="settleType"
        label="结算方式">
      </el-table-column>

      <el-table-column
        width="90"
        label="联系人"
        prop="contactMan"
      >
      </el-table-column>
      <el-table-column
        width="120"
        prop="contactPhone"
        label="联系电话">
      </el-table-column>
      <el-table-column
        align="left"
        show-overflow-tooltip
        class-name="status-col"
        width="280"
        label="联系地址">
        <template slot-scope="{row}">
          <span>{{ row.province + row.city + row.area + row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="left" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="webType">
            <template v-if="!isChoose">
          <el-button @click="handleUpdate(row)" type="primary" size="mini">
            编辑
          </el-button>
          <el-button @click="editStatus(row.id,'0')" type="danger" v-if="row.enable==1" size="mini">
            禁用
          </el-button>
          <el-button type="success" @click="editStatus(row.id,'1')" v-else="row.enable==0" size="mini">
            启用
          </el-button>

            </template>
            <template v-else>
              <el-button @click="chooseThis(row)" type="primary" size="mini">
                选择
              </el-button>
            </template>
          </template>
          <template v-else>
            <el-button @click="ERPChoose(row)" type="primary" size="mini">
              选择
            </el-button>
          </template>

        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getOutsideProcessingInfo" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <el-form label-width="130px" label-position="right">
        <el-row>
          <el-col :span="12">
            <el-form-item label="外协厂名称">
              <el-input v-model="form.outAssistName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产能设置">
              <el-input v-model="form.capacity"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加工厂类型">
              <el-select v-model="form.assistType" filterable placeholder="请选择">
                <el-option
                  v-for="item in optionsData"
                  :key="item.id"
                  :label="item.title"
                  :value="item.title+','+item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="加工类型">
              <el-input v-model="form.workType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加工厂等级">
              <el-input v-model="form.workQuality"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据直接下达">
              <el-checkbox :true-label="1" :false-label="0" v-model="form.submitOnAllocation"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据需要辅料审核">
              <el-checkbox :true-label="1" :false-label="0" v-model="form.needPackMaterial"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序">
              <el-input type="number" v-model="form.sortIndex"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式">
              <el-input v-model="form.settleType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="form.contactMan"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="form.contactPhone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="省/市/区:" class="postInfo-container-item">
                <el-cascader
                  style="width: 100%"
                  :options="options"
                  v-model="selectedOptions"
                  @change="handleChange">
                </el-cascader>
              </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="具体地址">
              <el-input v-model="form.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="同步通信url">
            <el-input :disabled="!permissionFlag" v-model="form.contractUrl"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="数据源">
            <el-input :disabled="!permissionFlag" v-model="form.dataBaseAlias"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="分表策略">
            <el-input :disabled="!permissionFlag" v-model="form.shardingKey"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="dialogStatus!=1" :span="24">
          <el-form-item label="同步通信key">
            <span style="width: 220px">{{form.factorySyncKey}}</span>
            <el-button size="mini" @click="getKey" type="primary">生成key</el-button>
          </el-form-item>
        </el-col>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn():editBtn()">确 定</el-button>
      </div>
    </el-dialog>
<!--    <servicedialog @tableRefresh="tableRefresh" ref="menuDialog" :dialogStatus="dialogStatus" :menuId="menuId" :titleDialog="titleDialog" :dialogVisible="dialogVisible"/>-->
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import { getOutsideProcessingInfoList, addOutsideProcessingInfo, updateOutsideProcessingInfo, getOutsideProcessingInfoById,generateOutAssistSyncKey } from '@/api/baseInfo/outsideProcessingInfo.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from '@/components/Pagination'
import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'
import {ifPermission} from "@/api/order/orderList";

export default {
  components: {
    Cancledialog, Pagination
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permissionFlag:false,
      adrValue: '',
      selectedOptions: [],
      options: regionData, // 地址地区信息
      webType: true,
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      search: {
        keyWord: ''
      },
      form: {
      },
      optionsData: [
        { id: 0, title: '印刷' },
        { id: 1, title: '后工' }
      ],

      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      confirmdialog: false,
      listLoading: false,
      tableData: [],
      menuId: ''
    }
  },
  mounted() {
    this.getOutsideProcessingInfo()
    if (this.$route.query.type === undefined) {
      this.webType = true
    } else {
      this.webType = false
    }
    this.checkPermission();
  },
  methods: {
    // 判断权限
    checkPermission() {
      const _that = this
      var data = {
        permission: 'outassist:modiSyncUrl'
      }
      ifPermission(data).then(res => {
        console.log(res)
        if (res.data == 1) {
          _that.permissionFlag = true;
        }else {
          _that.permissionFlag = false;
        }
      })
    },
    getKey(){
      const _that = this;
      var infoPost = {
        idOutAssist:_that.form.id
      }
      generateOutAssistSyncKey(infoPost).then(res => {
        console.log("generateOutAssistSyncKey",res);
        if (res.httpCode == 200) {
          _that.form.factorySyncKey = res.data.factorySyncKey
          _that.$message({
            message: '成功',
            type: 'success'
          })
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    iscityShow() {
      this.cityshow = false
      this.selected = []
      var t = setTimeout(() => {
        this.cityshow = true
      }, 0)
    },
    handleChange(value) {
      this.adrValue = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
      // console.log('adrValue', this.adrValue)
    },
    // 获取列表
    getOutsideProcessingInfo() {
      const _that = this
      _that.listLoading = true
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      if (_that.search.keyWord) {
        var data = {
          'params': JSON.stringify(params),
          'page': JSON.stringify(page)
        }
      } else {
        var data = {
          'params': {},
          'page': JSON.stringify(page)
        }
      }
      getOutsideProcessingInfoList(data).then(response => {
        console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // //console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },
    // 增加外加工档案
    handleCreateAdd() {
      const _that = this
      _that.form = {
      }
      _that.dialogTitle = '增加外加工档案'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
    },
    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getOutsideProcessingInfo()
    },
    // 增加档案
    addBtn() {
      const _that = this;

      var info = {
        capacity:_that.form.capacity,
        factorySyncKey:_that.form.factorySyncKey,
        outAssistName: _that.form.outAssistName,
        assistType: _that.form.assistType.split(',')[1],
        workType: _that.form.workType,
        workQuality: _that.form.workQuality,
        settleType: _that.form.settleType,
        contactMan: _that.form.contactMan,
        contactPhone: _that.form.contactPhone,
        province: _that.adrValue.split('/')[0],
        city: _that.adrValue.split('/')[1],
        area: _that.adrValue.split('/')[2],
        address: _that.form.address,
        remark: _that.form.remark,
        contractUrl: _that.form.contractUrl,
        dataBaseAlias: _that.form. dataBaseAlias,
        shardingKey: _that.form. shardingKey,
        submitOnAllocation: _that.form.submitOnAllocation,
        sortIndex: _that.form.sortIndex
      }
      var data = {
        'outAssistInfo': info
      }
      // //console.log(data);
      // return

      addOutsideProcessingInfo(data).then(res => {
        // //console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 唤起修改
    handleUpdate(row) {
      const _that = this

      _that.dialogTitle = '修改外加工档案'
      _that.dialogVisible = true
      _that.dialogStatus = '2'

      var idPrint = row.id
      var data = {
        idOutAssist: idPrint
      }
      getOutsideProcessingInfoById(data).then(res => {
        const data = res.data;
        console.log(res.data);
        var addressOption = []
        if(data.province!="null" && data.province!="" && data.province!=undefined){
          addressOption.push(TextToCode[data.province].code)
          addressOption.push(TextToCode[data.province][data.city].code)
          addressOption.push(TextToCode[data.province][data.city][data.area].code)
          _that.adrValue = data.province + "/" + data.city + "/" + data.area;
        }else {
          _that.adrValue = "";
        }

        // console.log(addressOption);
        // _that.addressInfo.selectedOptions = addressOption;
        _that.selectedOptions = addressOption;

        if(data.assistType==1){
          var assistTypeName = "后工";
        }else{
          var assistTypeName = "印刷";
        }
        console.log(assistTypeName);
        _that.form = {
          id: data.id,
          capacity: data.capacity,
          factorySyncKey:data.factorySyncKey,
          assistType:assistTypeName,
          assistTypeNum:data.assistType,
          outAssistName: data.outAssistName,
          workQuality: data.workQuality,
          workType: data.workType,
          settleType: data.settleType,
          contactMan: data.contactMan,
          contactPhone: data.contactPhone,
          address: data.address,
          remark: data.remark,
          contractUrl: data.contractUrl,
          dataBaseAlias: data.dataBaseAlias,
          shardingKey: data.shardingKey,
          submitOnAllocation: data.submitOnAllocation,
          needPackMaterial: data.needPackMaterial,
          sortIndex: data.sortIndex
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改档案
    editBtn() {
      const _that = this;
      _that.iscityShow();
      if (_that.form.assistType.split(',').length > 1) {
        var idType = _that.form.assistType.split(',')[1]
      } else {
        var idType = _that.form.assistTypeNum
      }
      var info = {
        id:_that.form.id,
        capacity: _that.form.capacity,
        outAssistName: _that.form.outAssistName,
        assistType:idType,
        factorySyncKey:_that.form.factorySyncKey,
        workType: _that.form.workType,
        workQuality: _that.form.workQuality,
        settleType: _that.form.settleType,
        contactMan: _that.form.contactMan,
        contactPhone: _that.form.contactPhone,
        province: _that.adrValue.split('/')[0],
        city: _that.adrValue.split('/')[1],
        area: _that.adrValue.split('/')[2],
        address: _that.form.address,
        remark: _that.form.remark,
        contractUrl: _that.form.contractUrl,
        dataBaseAlias: _that.form.dataBaseAlias,
        shardingKey: _that.form.shardingKey,
        submitOnAllocation: _that.form.submitOnAllocation,
        needPackMaterial: _that.form.needPackMaterial,
        sortIndex: _that.form.sortIndex
      }
      // console.log(info);
      // return
      var infoData = JSON.stringify(info);
      var infoPost = {
        'outAssistInfo': infoData
      }
      // var data = {
      //   'outAssistInfo': info
      // }
      // var info = JSON.stringify(_that.form)
      // var data = {
      //   'outsideProcessInfo': info
      // }
      // // console.log(data);

      updateOutsideProcessingInfo(infoPost).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 启用禁用
    editStatus(id, status) {
      var _that = this
      var printerTypeInfo = {
        id: id,
        enable: status
      }
      var params = {
        'outAssistInfo': JSON.stringify(printerTypeInfo)
      }

      var url = '/doc/enableOutAssistInfo'
      _that.$refs.confirmDialog.updataClick(params, url)
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getOutsideProcessingInfo()
    },
    // 弹窗内选择操作
    chooseThis(row) {
      // console.log('点击选择');
      this.$emit('chooseOutsideProcessing', row)
    },
    ERPChoose(row) {
      // this.$message.error(row)
      dyERP.sendJson(JSON.stringify(row))
    }
  }
}
</script>

<style lang="scss" scoped>
  .filter-container {
    margin-bottom: 15px;
  }
</style>
