<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的报送任务</span>
      </div>
      <div>
        <el-select
          v-model="pageForm.org"
          placeholder="报送部门"
          @change="handleFilter"
          clearable
        >
          <el-option
            v-for="item in orgData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
      <el-table
        v-loading="listLoading"
        :data="taskList.results"
        border
        fit
        stripe
        highlight-current-row
        max-height="300"
        @row-click="clickRow"
      >
        <el-table-column type="index" width="50"/>
        <el-table-column label="任务名称">
          <template #default="scope">
            <span v-if="scope.row.qtask_">{{scope.row.qtask_.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态">
          <template #default="scope">
            <span v-if="scope.row.qtask_">{{scope.row.qtask_.state}}</span>
          </template>
        </el-table-column>
        <el-table-column label="截止日期">
          <template #default="scope">
            <span v-if="scope.row.qtask_">{{scope.row.qtask_.end_date}}</span>
          </template>
        </el-table-column>
        <el-table-column label="报送部门">
          <template #default="scope">
            <span v-if="scope.row.org_">{{scope.row.org_.name}}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="taskList.count"
        :page.sync="pageForm.page"
        :limit.sync="pageForm.page_size"
        @pagination="getrecordlist"
      />
    </el-card>
    <el-card style="margin-top:6px">
      <div slot="header" class="clearfix">
        <span v-if="qtaskName!==''" style="display: inline-block;line-height: 40px">【{{qtaskName}}】</span>
        <span style="display: inline-block;line-height: 40px">记录详情</span>
        <el-button
          v-if="buttonsShow&&checkPermission(['qaction_create'])"
          type="primary"
          style="float: right"
          @click="serviceUpdate(scope)"
        >
          更新服务
        </el-button>
        <el-button
          v-if="buttonsShow&&checkPermission(['qaction_create'])"
          type="primary"
          style="float: right;margin-right: 10px"
          @click="qualiUpdate(scope)"
        >
          编辑资质
        </el-button>
        <el-button
          v-if="buttonsShow&&checkPermission(['qaction_create'])"
          type="primary"
          style="float: right;margin-right: 10px"
          @click="qualiCreate(scope)"
        >
          新增资质
        </el-button>
        <el-button
          v-if="buttonsShow&&checkPermission(['qaction_create'])"
          type="primary"
          style="float: right;margin-right: 10px"
          @click="abilityCreate(scope)"
        >
          新增能力
        </el-button>
      </div>
      <el-table
        style="margin-top: 6px"
        v-loading="listLoading"
        :data="recordList.results"
        border
        fit
        stripe
        highlight-current-row
        max-height="400"
      >
        <el-table-column type="index" width="50" />

        <el-table-column width="150px" label="任务标题">
          <template>{{qtaskName}}</template>
        </el-table-column>
        <el-table-column label="操作类型">
          <template slot-scope="scope">
            <span v-if="scope.row.action==='ablity:create'">新增能力</span>
            <span v-else-if="scope.row.action==='service:update'">更新服务</span>
            <span v-else-if="scope.row.action==='quali:update'">更新资质</span>
            <span v-else-if="scope.row.action==='quali:create'">新增资质</span>
          </template>
        </el-table-column>
        <el-table-column label="确认情况">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.confirmed" effect="plain">已确认</el-tag>
            <el-tag type="danger" effect="plain" v-else>未确认</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="改动内容">
          <template #default="scope">
            <span v-if="scope.row.value2.name">{{ scope.row.value2.name }}</span>
            <span v-else>{{ scope.row.value2 }}</span>
          </template>

        </el-table-column>
        <el-table-column label="报送文件">
          <template slot-scope="scope" v-if="scope.row.files">
            <el-link
              v-if="scope.row.files.length > 1"
              @click="handleRecord({ action: 'view', record: scope.row })"
            >有
              <span style="color: red">{{ scope.row.files.length }}</span>
              个文件</el-link
            >
            <div v-else v-for="item in scope.row.files_" v-bind:key="item.id">
              <el-link :href="item.path" target="_blank" type="primary">
                {{item.name }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作人">
          <template slot-scope="scope">{{ scope.row.content_name }}</template>
        </el-table-column>
        <el-table-column label="操作时间">
          <template slot-scope="scope" >{{ scope.row.update_time.substring(0, 16) }}</template>
        </el-table-column>

        <el-table-column
          align="center"
          label="操作"
          width="60px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link
              v-if="!scope.row.confirmed"
              type="danger"
              size="small"
              @click="handleDelete( scope.row.id )"
            >删除</el-link>
          </template>

        </el-table-column>
      </el-table>
      <pagination
        :total="recordList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
      <el-drawer
        title="记录"
        :visible.sync="drawer"
        :with-header="false"
        size="40%"
      >
        <recorddo
          ref="recorddo"
          :data="data"
          @handleDo="handleDo"
          v-if="drawer"
        ></recorddo>
      </el-drawer>
    </el-card>
    <el-dialog
      :visible.sync="dialogVisibleAbility"
      title="新增能力"
    >
      <el-form
        ref="abilityForm"
        :model="abilityForm"
        label-width="80px"
        label-position="right"
        :rules="rule"
      >
        <el-form-item label="能力类型" prop="atype">
          <el-select
            style="width: 100%;"
            v-model="abilityForm.atype"
            placeholder="能力类型"
          >
            <el-option
              v-for="item in atypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="能力领域" prop="afield">
          <el-select
            style="width: 100%;"
            v-model="abilityForm.afield"
            placeholder="能力领域"
          >
            <el-option
              v-for="item in afieldOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="能力文件" prop="file">
          <el-upload
            ref="upload"
            :action="upUrl"
            :on-preview="handlePreview"
            :on-success="handleUpSuccess"
            :on-remove="handleRemove"
            :headers="upHeaders"
            :file-list="fileLista"
            :limit="1"
            accept=".xls,.xlsx"
          >
            <el-button size="small" type="primary">上传文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="新增数量">
          <el-input-number v-model="abilityForm.num" :min="1" label="新增数量"></el-input-number>
        </el-form-item>

      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisibleAbility = false">取消</el-button>
        <el-button type="primary" @click="confirmAbility('abilityForm')">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      title="新增资质"
    >
      <el-form
        ref="Form"
        :model="qualiForm"
        label-width="80px"
        label-position="right"
        :rules="rule"
      >
        <el-form-item label="资质类型" prop="type">
          <el-select
            style="width: 100%;"
            v-model="qualiForm.type"
            placeholder="资质类型"
            @change="qualiTypeChange"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资质名称" prop="name" v-if="qualiForm.type==='OTHER'">
          <el-input v-model="qualiForm.name" placeholder="资质名称"/>
        </el-form-item>
        <el-form-item label="资质等级" v-if="qualiForm.type!=='OTHER'">
          <el-select
            style="width: 100%;"
            v-model="qualiForm.grade"
            placeholder="资质类型"
          >
            <el-option
              v-for="item in gradeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="等级" v-if="qualiForm.type==='OTHER'">
          <el-input v-model="qualiForm.level" placeholder="等级"/>
        </el-form-item>
        <el-form-item label="资质范围">
          <el-input
            type="textarea"
            :rows="4"
            v-model="qualiForm.scope"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            :rows="4"
            v-model="qualiForm.description"
            placeholder="描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="备案城市" v-if="qualiForm.type==='OTHER'">
          <el-select
            v-model="qualiForm.province"
            placeholder="省份"
            clearable
            @change="getCites(qualiForm.province)"
          >
            <el-option
              v-for="item in proviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select
            v-model="qualiForm.city"
            placeholder="所在市"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在省" v-if="qualiForm.grade===20">
          <el-select
            v-model="qualiForm.province"
            placeholder="省份"
            clearable
            style="width: 100%"
            @change="getCites(qualiForm.province)"
          >
            <el-option
              v-for="item in proviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在市" v-if="qualiForm.grade===30">
          <el-select
            style="width: 100%;"
            v-model="qualiForm.city"
            placeholder="所在市"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisibleQuliEdit"
      title="编辑资质"
    >
      <el-table
        v-if="!showForm"
        :data="quliList"
        fit
        stripe
        highlight-current-row
      >
        <el-table-column label="我的资质" prop="name">
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >编辑</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-form
        v-if="showForm"
        ref="Form"
        :model="qualiForm"
        label-width="80px"
        label-position="right"
        :rules="rule"
      >
        <el-form-item label="资质类型" prop="type">
          <el-select
            style="width: 100%;"
            v-model="qualiForm.type"
            placeholder="资质类型"
            @change="qualiTypeChange"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资质名称" prop="name" v-if="qualiForm.type==='OTHER'">
          <el-input v-model="qualiForm.name" placeholder="资质名称"/>
        </el-form-item>
        <el-form-item label="资质等级" v-if="qualiForm.type!=='OTHER'">
          <el-select
            style="width: 100%;"
            v-model="qualiForm.grade"
            placeholder="资质类型"
          >
            <el-option
              v-for="item in gradeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="等级" v-if="qualiForm.type==='OTHER'">
          <el-input v-model="qualiForm.level" placeholder="等级"/>
        </el-form-item>
        <el-form-item label="资质范围">
          <el-input
            type="textarea"
            :rows="4"
            v-model="qualiForm.scope"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            type="textarea"
            :rows="4"
            v-model="qualiForm.description"
            placeholder="描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="备案城市" v-if="qualiForm.type==='OTHER'">
          <el-select
            v-model="qualiForm.province"
            placeholder="省份"
            clearable
            @change="getCites(qualiForm.province)"
          >
            <el-option
              v-for="item in proviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select
            v-model="qualiForm.city"
            placeholder="所在市"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在省" v-if="qualiForm.grade===20">
          <el-select
            v-model="qualiForm.province"
            placeholder="省份"
            clearable
            style="width: 100%"
            @change="getCites(qualiForm.province)"
          >
            <el-option
              v-for="item in proviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在市" v-if="qualiForm.grade===30">
          <el-select
            style="width: 100%;"
            v-model="qualiForm.city"
            placeholder="所在市"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisibleQuliEdit = false">取消</el-button>
        <el-button v-if="showForm" type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisibleSever"
      title="编辑服务"
    >
      <el-form
        ref="severForm"
        :model="severForm"
        label-width="80px"
        label-position="right"
        :rules="rule"
      >
        <el-form-item label="服务内容" prop="value2">
          <el-input
            type="textarea"
            :rows="4"
            v-model="severForm.value2"
            placeholder="服务内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisibleSever = false">取消</el-button>
        <el-button type="primary" @click="submitEditSever('severForm')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getQtaskMy, getQtask,qactionMy, getQualityMy,createQuali,qactionDelete,updateQuali, createAbility, updateService,provinceLists,cityLists} from "@/api/ability";
  import {getDictList} from "@/api/dict";
  import {genTree} from "@/utils";
  import {getOrgList} from "@/api/org";
  import {getCMAGroup} from "@/api/cma";
  import checkPermission from "@/utils/permission";
  import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {upUrl, upHeaders} from "@/api/file";

  export default {
    components: {Pagination, Treeselect},
    name: "mQualityTask",
    data() {
      return {
        upHeaders: upHeaders(),
        upUrl: upUrl(),
        qtask: null,
        checkedItem:null,
        pageForm: {
          page: 1,
          page_size: 10,
          org: '',
        },
        listQuery:{
          page: 1,
          page_size: 10,
          task:null,
        },
        quliList: [],
        orgData: [],
        fileList: [],
        cityOptions: [],
        proviceOptions:[],
        fileLista: [],
        updateId: null,
        taskList: {count: 0,},
        recordList: {count: 0,},
        drawer: false,
        showForm: false,
        multiple: true,
        listLoading: false,
        dialogVisible: false,
        dialogVisibleSever: false,
        dialogVisibleAbility: false,
        dialogVisibleQuliEdit: false,
        dialogType: "new",
        severForm:{
          qtask:null,
          value2:'',
        },
        qualiForm: {
          name: "",
          type: "",
          grade:null,
          scope: "",
          level: "",
          province: "",
          city: "",
          description: "",
          citys: [],
        },
        abilityForm: {
          atype: '',
          afield: '',
          file: '',
          num: '',
          qtask: '',
        },
        rule: {
          name: [{required: true, message: "请输入名称", trigger: "blur"}],
          orgs: [{required: true, message: "请选择上报公司", trigger: "blur"}],
          atype: [{required: true, message: "请选择类型", trigger: "blur"}],
          afield: [{required: true, message: "请选择能力领域", trigger: "blur"}],
          value2: [{required: true, message: "请填写更新内容", trigger: "blur"}],
        },
        stateOptions: [
          '待发布',
          '进行中',
          '已关闭',
        ],
        typeOptions: [
          'CMA',
          'CNAS',
          'OTHER'
        ],
        atypeOptions:[],
        afieldOptions: [],//领域
        gradeOptions: [
          {id:10,name:'国家级'},{id:20,name:'省级'},{id:30,name:'市级'}
        ],//等级
        qtaskName: "",
        filterOrgText: "",
        treeLoding: false,
        buttonsShow: false,
      }
    },
    mounted() {
      this.getTableList();
      this.getGroup();
      //领域类型
      this.atypeOptions = [];
      this.afieldOptions = [];
      this.getOptions();
      this.getProvince();
    },

    methods: {
      getOptions(){
        getDictList({type__code: "field_type",is_used:true}).then((res) => {
          this.afieldOptions  = genTree(res.data);
        });
        getDictList({type__code: "quality_type",is_used:true}).then((res) => {
          this.atypeOptions = genTree(res.data);
        });
      },
      getProvince(){
        provinceLists({page:1,page_size:60}).then(res=>{
          this.proviceOptions = res.data.results;
        })
      },
      getCites(province){
        this.qualiForm.city ='';
        cityLists({parent:province,page:1,page_size:100}).then(res=>{
          this.cityOptions = res.data.results;
        })
      },
      handlePreview(file) {
        if ("url" in file) {
          window.open(file.url);
        } else {
          window.open(file.response.data.path);
        }
      },
      handleUpSuccess(res, file, filelist) {
        this.abilityForm.file = res.data.id;
      },
      handleRemove(file, filelist) {
        this.abilityForm.file = null;
      },
      checkPermission,
      getTableList() {
        this.listLoading = true;
        getQtaskMy(this.pageForm).then((response) => {
          if (response.data) {
            debugger;
            this.taskList = response.data;
          }
          this.listLoading = false;
        });
      },
      getGroup() {
        getOrgList({can_supervision: true}).then((res) => {
          this.orgData = res.data;
        });
      },
      getrecordlist() {
        this.getTableList();
      },
      handleFilter() {
        this.getTableList();
      },
      clickRow(obj){
        this.checkedItem = obj;
        this.qtask = obj.qtask;
        this.qtaskName = obj.qtask_.name;
        this.buttonsShow = true;
        this.listQuery.task =  obj.qtask;
        qactionMy(this.listQuery).then((res)=>{
          this.recordList = res.data;
        })
      },

      ///////
      getList(){
        this.qtask = obj.qtask;
        this.listQuery.task =  obj.qtask;
        qactionMy(this.listQuery).then((res)=>{
          this.recordList = res.data;
        })
      },
      //更新服务
      serviceUpdate() {
        this.dialogVisibleSever = true;
      },
      //更新服务提交
      submitEditSever(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.severForm.qtask = this.qtask;
            updateService(this.severForm).then((res) => {
              if (res.code >= 200) {
                this.dialogVisibleSever = false;
                this.$message.success("成功");
              }
            });
          } else {
            return false;
          }
        });
      },
      //新增资质
      qualiCreate() {
        this.dialogType = 'new';
        this.dialogVisible = true;
      },
      //编辑资质
      qualiUpdate() {
        this.dialogType = 'edit';
        this.showForm = false;
        this.dialogVisibleQuliEdit = true;
        this.getQuliList();
      },
      getQuliList(){
        getQualityMy().then(res=>{
          this.quliList = res.data.results;
        })
      },
      //更改资质类型
      qualiTypeChange(){
        if(this.qualiForm.type==='OTHER'){
          this.qualiForm.grade = '';
          this.qualiForm.city = '';
          this.qualiForm.province = '';
        }
      },
      //编辑资质
      handleEdit(row){
        this.showForm = true;
        this.qualiForm.id= row.id;
        this.qualiForm.name= row.name;
        this.qualiForm.type= row.type;
        this.qualiForm.grade =row.grade;
        this.qualiForm.scope= row.scope;
        this.qualiForm.level=row.level;
        this.qualiForm.province=row.province;
        this.qualiForm.city=row.city;
        this.qualiForm.description=row.description;
        this.qualiForm.citys=row.citys;
        cityLists({parent:row.province,page:1,page_size:100}).then(res=>{
          this.cityOptions = res.data.results;
        })
      },
      //新增能力
      abilityCreate() {
        this.dialogVisibleAbility = true;
      },
      //提交资质
      async confirm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if(this.qualiForm.type==='OTHER'){
              let city = parseInt(this.qualiForm.city);
              let province = parseInt(this.qualiForm.province);
              this.qualiForm.citys.push(province);
              this.qualiForm.citys.push(city);
            }else{}
            let obj = new Object();
            obj.qtask = this.qtask;
            obj.value2 = this.qualiForm;
            if(obj.value2.grade===''){
              obj.value2.grade=null
            }
            const isEdit = this.dialogType === "edit";
            if (isEdit) {
              updateQuali(obj).then((res) => {
                if (res.code >= 200) {
                  this.getTableList();
                  this.dialogVisibleQuliEdit = false;
                  this.$message.success("成功");
                }
              });
            } else {
              debugger;
              console.log(obj)
              createQuali(obj).then((res) => {
                if (res.code >= 200) {
                  this.getTableList();
                  this.dialogVisible = false;
                  this.$message.success("成功");
                }
              });
            }
          } else {
            return false;
          }
        });
      },
      //提交服务更新
      async confirmAbility(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.abilityForm.qtask = this.qtask;
            createAbility(this.abilityForm).then((res) => {
              if (res.code >= 200) {
                this.getTableList();
                this.dialogVisibleAbility = false;
                this.$message.success("成功");
              }
            });
          } else {
            return false;
          }
        });
      },
      //删除操作
      handleDelete(id){
        this.$confirm("确认删除该操作吗?", "提示")
          .then(async () => {
            await qactionDelete(id);
            location.reload();
            this.$message.success("成功");
          })
          .catch((err) => {
            console.error(err);
          });
      },
    },
  }
</script>

<style scoped>

</style>
