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

      <el-input v-model="search.keyWord" placeholder="关键字" 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>
    <div class="table-con">
      <el-table
        :data="tableData"
        v-loading="listLoading"
        style="width: 100%;margin-bottom: 20px;"
        border
      >
        <el-table-column
          label="#"
          align="center"
          type="index"
          :index="indexMethod">
        </el-table-column>
        <el-table-column label="操作" align="left" width="250" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <template v-if="webType">
              <template v-if="!isChoose">
            <el-button @click="handleUpdate(row.id)" type="primary" size="mini">
              编辑
            </el-button>
            <el-button @click="dockingBtn(row)" type="primary" size="mini">
              对接工序
            </el-button>
            <el-button @click="editStatus(row.id,'1')" type="danger" v-if="row.voidFlag==0" size="mini">
              禁用
            </el-button>
            <el-button @click="editStatus(row.id,'0')" v-else-if="row.voidFlag==1" size="mini">
              启用
            </el-button>
              </template>
              <template v-else>
                <el-button @click="sourceType == 1? chooseThisTo(row):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-column align="center" label="状态" class-name="status-col" width="100">
          <template slot-scope="{row}">
            <el-tag v-if="row.voidFlag==0" type="success">
              启用中
            </el-tag>
            <el-tag v-else="row.voidFlag==1" type="danger">
              禁用中
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="factoryName"
          label="厂名称">
        </el-table-column>
        <el-table-column
          prop="contactUrl"
          label="同步外协地址">
        </el-table-column>
        <el-table-column
          width="300px"
          prop="contactKey"
          label="同步通信key">
        </el-table-column>
        <el-table-column
          label="创建时间"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.createTime">{{ scope.row.createTime | getTime }}</span>
          </template>
        </el-table-column>

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

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="850px">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>外协来源厂档案</span>
        </div>
        <div>
          <el-form label-width="130px" label-position="right">
            <el-row>
              <el-col :span="12">
                <el-form-item label="厂名称">
                  <el-input :disabled="selectDisabled" v-model="form.factoryName"></el-input>
                </el-form-item>
                <!--                <el-form-item label="选择来源厂">-->
                <!--                  <el-select :disabled="selectDisabled" v-model="form.itemName" filterable placeholder="请选择">-->
                <!--                    <el-option-->
                <!--                      v-for="item in options"-->
                <!--                      :key="item.id"-->
                <!--                      :label="item.itemName"-->
                <!--                      :value="item.itemName+','+item.id">-->
                <!--                    </el-option>-->
                <!--                  </el-select>-->
                <!--                </el-form-item>-->
              </el-col>
              <el-col :span="12">
                <el-form-item label="同步通信地址">
                  <el-input v-model="form.contactUrl"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="DataBaseAlias">
                  <el-input :disabled="selectDisabled" v-model="form.dataBaseAlias"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="ShardingKey">
                  <el-input :disabled="selectDisabled" v-model="form.shardingKey"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="同步加密key">
                  <el-input v-model="form.contactKey"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>


      <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>
    <!--    <el-card style="margin-top: 30px" class="box-card">-->
    <!--      <div slot="header" class="clearfix">-->
    <!--        <span>来源厂后工工序列表</span>-->
    <!--      </div>-->
    <!--      <div>-->
    <!--      </div>-->
    <!--    </el-card>-->
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
    <el-dialog title="配置来源厂与本地工艺对照表" :visible.sync="dialogVisible2" width="550px">
      <el-button @click="batcxBtn" size="mini" style="margin-top: -15px;margin-bottom: 10px" type="primary">批量对应
      </el-button>
      <el-table
        size="mini"
        border
        :data="optionsData"
        style="width: 100%">
        <el-table-column label="操作" align="left" width="130" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button @click="dockingOldBtn(scope.$index)" type="primary" size="mini">
              选择本厂工序
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="processName"
          label="来源厂工序名称"
          width="100">
        </el-table-column>
        <el-table-column
          align="center"
          prop="procedureName"
          label="本厂工序名称"
          width="80">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          width="180">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">关 闭</el-button>
        <el-button type="primary" @click="configBtn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="本厂工序列表" :visible.sync="dialogVisible3" width="600px">
      <el-card class="box-card">
        <div>
          <el-form label-width="130px" label-position="right">
            <el-row>
              <el-col :span="12">
                <!--                <el-form-item label="厂名称">-->
                <!--                  <el-input  v-model="form.factoryName"></el-input>-->
                <!--                </el-form-item>-->
                <el-form-item label="选择本厂工序">
                  <el-select v-model="form.craftName" filterable placeholder="请选择">
                    <el-option
                      v-for="item in craftInfoList"
                      :key="item.id"
                      :label="item.craftName"
                      :value="item.craftName+','+item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-card>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="craftNameBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addInfo,
  configCorrespondInfo,
  getCraftInfoList,
  getERPSupplierList,
  getInfo,
  getInfoById,
  queryRemoteWorkProcessList,
  updateInfo,
  getOriginFactory
} from '@/api/baseInfo/originFactories/index.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import Pagination from "@/components/Pagination/index";

export default {
  name: "originFactories",
  components: {
    Cancledialog, Pagination
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    },
    /**
     * 调用来源
     * 0 普通调用
     * 1 查询统计调用
     */
    sourceType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      webType: true,
      originFactoryName: "",
      idOriginFactory: "",
      scopeIndex: 999,
      dialogVisible3: false,
      craftInfoList: [],
      optionsData: [],
      dialogVisible2: false,
      selectDisabled: false,
      options: [],
      dialogStatus: 1,//1增加，2修改
      form: {
        id: 0,
        factoryName: '',
        contactUrl: '',
        dataBaseAlias: '',
        shardingKey: '',
        contactKey: ''
      },
      confirmdialog: false,
      dialogVisible: false,
      dialogTitle: "",
      listLoading: false,
      tableData: [],
      search: {
        keyWord: ''
      },
      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      }
    }
  },
  mounted() {
    this.getTableInfo();
    if (this.$route.query.type === undefined) {
      this.webType = true
    } else {
      this.webType = false
    }
    // this.getERPSupplierList();
  },
  methods: {
    batcxBtn() {
      var _that = this;
      //craftName
      var params = {};
      var data = {
        "params": JSON.stringify(params),
      }
      getCraftInfoList(data).then(res => {
        //获取详情
        var datas = res.data;
        _that.craftInfoList = res.data;
        res.data.forEach(item => {
          for (let i = 0; i < _that.optionsData.length; i++) {
            var datas = _that.optionsData[i];
            if (item.craftName == datas.processName) {
              _that.$set(_that.optionsData[i], 'procedureName', item.craftName);
              _that.$set(_that.optionsData[i], 'procedureId', item.id);
            }
          }
        })
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    configBtn() {
      var _that = this;
      var params = {};
      var correspondInfoList = [];
      for (let i = 0; i < _that.optionsData.length; i++) {
        var datas = _that.optionsData[i];
        if(datas.processName && datas.procedureName){
          var correspondInfo = {
            idOriginFactory: _that.idOriginFactory,
            originFactoryName: _that.originFactoryName,
            idOriginProcess: datas.id,
            originProcessName: datas.processName,
            idCraftInfo: datas.procedureId,
          }
          correspondInfoList.push(correspondInfo);
        }

      }
      var data = {
        "idOriginFactory": _that.idOriginFactory,
        "correspondInfoList": JSON.stringify(correspondInfoList),
      }
      configCorrespondInfo(data).then(res => {
        _that.dialogVisible2 = false;
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '成功',
            type: 'success'
          });
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    craftNameBtn() {
      var _that = this;
      if (!_that.form.craftName) {
        _that.$message("请选择本厂工序");
        return;
      }
      _that.$set(_that.optionsData[_that.scopeIndex], 'procedureName', _that.form.craftName.split(',')[0]);
      _that.$set(_that.optionsData[_that.scopeIndex], 'procedureId', _that.form.craftName.split(',')[1]);
      _that.dialogVisible3 = false;
    },
    dockingOldBtn(scopeIndex) {
      var _that = this;
      _that.craftInfoList = [];
      _that.form = {};
      _that.scopeIndex = scopeIndex;
      var params = {};
      _that.dialogVisible3 = true;
      var data = {
        "params": JSON.stringify(params),
      }
      getCraftInfoList(data).then(res => {
        //获取详情
        var datas = res.data;
        _that.craftInfoList = res.data;
        // console.log("_that.options",_that.craftInfoList);
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    dockingBtn(row) {
      var _that = this;
      _that.byId = row.id;
      _that.dialogVisible2 = true;
      _that.idOriginFactory = row.id;
      _that.originFactoryName = row.factoryName;
      var data = {
        idOriginFactory: row.id
      }
      queryRemoteWorkProcessList(data).then(res => {
        //获取详情
        var datas = res.data;
        _that.optionsData = res.data;
        // console.log("_that.options",_that.optionsData);getOriginFactory
        getOriginFactory(data).then(res => {
          //获取详情
          res.data.correspondInfoList.forEach(item => {
            for (let i = 0; i < _that.optionsData.length; i++) {
              var datas = _that.optionsData[i];
              if (item.idOriginProcess == datas.id) {
                _that.$set(_that.optionsData[i], 'procedureName', item.craftName);
                _that.$set(_that.optionsData[i], 'procedureId', item.idCraftInfo);
              }
            }
          })
        }).catch(err => {
          _that.$message.error(err)
        })
      }).catch(err => {
        _that.$message.error(err)
      })

    },
    //启用禁用
    editStatus(id, status) {
      var _that = this;
      var data = {
        id: id,
        voidFlag: status
      }
      var params = {
        "originFactory": JSON.stringify(data),
      }

      var url = '/outassistDoc/voidOriginFactory';
      _that.$refs.confirmDialog.updataClick(params, url);
    },
    handleUpdate(id) {
      const _that = this
      _that.dialogTitle = '修改外协厂信息'
      _that.dialogVisible = true
      _that.dialogStatus = '2';
      _that.selectDisabled = true;
      _that.byId = id
      var data = {
        idOriginFactory: id
      }
      getInfoById(data).then(res => {
        //获取详情
        var datas = res.data;
        // console.log(datas);
        _that.form = {
          id: id,
          factoryName: datas.factoryName,
          contactUrl: datas.contactUrl,
          dataBaseAlias: datas.dataBaseAlias,
          shardingKey: datas.shardingKey,
          contactKey: datas.contactKey
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    editBtn() {
      //修改
      const _that = this;
      var info = JSON.stringify(_that.form)
      var originFactory = {
        id: _that.form.id,
        contactKey: _that.form.contactKey
      };
      var data = {
        "originFactory": info
      }
      // console.log(data);

      updateInfo(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          });
          _that.getTableInfo();
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },
    addBtn() {
      //增加
      const _that = this;
      // console.log(_that.form.itemName.split(',')[1]);
      // console.log(_that.form);
      // var info =JSON.stringify(_that.form.contactKey)
      // var originFactory = {
      //   contactKey: _that.form.contactKey
      // };
      // var infos = {
      //   "originFactory": JSON.stringify(originFactory),
      //   "idERPSupplier": _that.form.itemName.split(',')[1]
      // }
      // console.log("clientLevel",data);
      var infos = {
        originFactory: JSON.stringify(_that.form)
      }
      addInfo(infos).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          });
          _that.getTableInfo();
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },
    handleCreateAdd() {
      //增加外协厂来源
      const _that = this
      _that.form = {
        levelName: ''
      }
      _that.dialogTitle = '增加外协厂'
      _that.dialogStatus = '1';
      _that.dialogVisible = true;
      _that.selectDisabled = false;

    },
    //获取表格数据
    getTableInfo() {
      const _that = this
      _that.listLoading = true
      var params = _that.search;
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize,
      }
      var data = {
        "params": {},
        "page": JSON.stringify(page),
      }
      // console.log(data);
      getInfo(data).then(response => {
        // console.log("tableData",response)
        const data = response.data;
        // //  组合表单数据
        _that.tableData = data;
        _that.listData.total = response.total;
        // console.log(_that.tableData)
        _that.listLoading = false;
      }).catch(err => {
        _that.listLoading = false;
      })
    },
    getERPSupplierList() {
      const _that = this
      var infos = {}
      // console.log(data);
      getERPSupplierList(infos).then(response => {
        const getData = response.data;
        // console.log(getData);
        _that.options = response.data;
      }).catch(err => {

      })
    },
    //搜索
    searchData() {
      this.listData.page = 1;
      this.getTableInfo()
    },
    //序号
    indexMethod(index) {
      return index + 1;
    },
    //刷新表格
    tableRefresh() {
      //刷新变革
      this.getTableInfo()
    },

    // 弹窗内选择操作
    chooseThis(row) {
      // console.log('点击选择');
      this.$emit('choosePaper', row)
    },

    // 查询统计选择
    chooseThisTo(row) {
      var data = {
        id: row.id,
        name: row.factoryName
      }
      this.$emit('chooseRow', data)
    },
    ERPChoose(row) {
      // this.$message.error(row)
      dyERP.sendJson(JSON.stringify(row))
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #f0f2f5;
  padding: 30px;
  min-height: calc(100vh - 84px);
}

.filter-container {
  margin-bottom: 15px;
}
</style>
